贴一个最小费用最大流的代码。
问题: FJ从点1走到点n,再走回点1.
方法:设置一个起点s,一个终点t,在1和s以及n和t之间链接费用为2流为1的边,求s到t的最小费用最大流就行了。
直接上代码。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
bool Read ( int &x ) {
bool f = 0 ; x = 0 ; char c = getchar() ;
while ( !isdigit(c) ) {
if ( c == '-' ) f = 1 ;
if ( c == EOF ) return false ;
c = getchar() ;
}
while ( isdigit(c) ) {
x = 10 * x + c - '0' ;
c = getchar() ;
}
if ( f ) x = -x ;
return true ;
}
using namespace std;
#define maxn 1010
const int zhf = 100000000;
const int maxm = 100010 ;
int st[maxm], to[maxm], f[maxm], w[maxm], nxt[maxm] ;
int be[2010];
int ans,e;
int s,t,pre[2010];
bool p[maxn];
int d[maxn], n, m;
queue<int >q;
void add ( int x, int y, int cost, int flow ) {
to[++e] = y ;
nxt[e] = be[x] ;
be[x] = e ;
st[e] = x ;
w[e] = cost ;
f[e] = flow ;
}
void add_edge ( int x, int y, int cost, int flow ) {
add ( x, y, cost, flow ) ;
add ( y, x, -cost, 0 ) ;
}
bool spfa () {
memset ( p, 0, sizeof(p) ) ;
int i, j, k, x, y, z ;
for ( i = 0 ; i <= n + 4 ; i++ ) d[i] = zhf ;
d[s] = 0 ;
p[s] = 1 ;
pre[s] = -1 ;
q.push(s) ;
while ( !q.empty() ) {
int x = q.front() ;
q.pop() ;
p[x] = 0 ;
for ( i = be[x] ; i != -1 ; i = nxt[i] ) {
int y = to[i] ;
if ( d[y] > d[x] + w[i] && f[i] > 0 ) {
d[y] = d[x] + w[i] ;
pre[y] = i ;
if ( !p[y] ) {
p[y] = 1 ;
q.push(y) ;
}
}
}
}
if ( d[t] != zhf ) return true ;
return false ;
}
void Find () {
int i, j, k ;
for ( i = pre[t] ; i != -1 ; i = pre[st[i]] ) {
f[i] -= 1 ;
f[i+1] += 1 ;
ans += w[i] ;
}
}
int main () {
int i, j, k, x, y, z ;
Read(n) ; Read(m) ;
e = 0 ;
ans = 0 ;
s = 0 ; t = n + 1 ;
memset ( be, -1, sizeof(be) ) ;
for ( i = 1 ; i <= m ; i ++ ) {
Read(x) ; Read(y) ; Read(z) ;
add_edge ( x, y, z, 1 ) ;
add_edge ( y, x, z, 1 ) ;
}
add_edge ( s, 1, 0, 2 ) ;
add_edge ( n, t, 0, 2 ) ;
while ( spfa() ) {
Find() ;
}
printf ( "%d\n", ans ) ;
return 0 ;
}