max_flow模板(POJ 1273)
C++ code:
#include <iostream> #include <cstdio> #include <cstring> using namespace std; long max_flow(); int M; long mat[201][201], d[201]; int main() { int N, i, S, E; long C; while(scanf("%d%d", &N, &M) == 2) { memset(mat, 0, sizeof(mat)); mat[0][1] = d[0] = 200000000; for(i = 1; i <= N; i++) { scanf("%d%d%ld", &S, &E, &C); mat[S][E] += C; } printf("%ld\n", max_flow()); } return 0; } long max_flow() { long flow[201][201], j; int i, pre[201], p, q, t, que[201]; memset(flow, 0, sizeof(flow)); for(;;) { for(i = p = q = t = 0; i <= M; pre[i++] = -1); for(; p <= q && pre[M] == -1; t = que[++p]) for(i = 1; i <= M; i++) if((j = mat[t][i] - flow[t][i]) && pre[i] == -1) { pre[que[++q] = i] = t; d[i] = d[t] < j ? d[t] : j; } else if((j = flow[i][t]) && pre[i] == -1) { pre[que[++q] = i] = -t; d[i] = d[t] < j ? d[t] : j; } if(p > q) break; for(i = M; i;) if(pre[i] >= 0) { flow[pre[i]][i] += d[M]; i = pre[i]; } else if(pre[i] < 0) { flow[i][-pre[i]] -= d[M]; i = -pre[i]; } } return flow[0][1]; }