poj 1273 Drainage Ditches 最大流
第一次写最大流,照着书上面敲。
用Edmonds_karp算法,每次通过bfs搜出一条增广路径加到流中,直到不能搜到为止。这题要注意有重边,多条重边要加在一起,用+=
#include <iostream> #include <queue> using namespace std; const int N = 205; const int INF = 1000000000; int c[N][N]; int flow[N][N]; int min_flow[N]; int pre[N]; int n, m; int max_flow() { memset(flow, 0, sizeof(flow)); int u; int ans = 0; while (1) { memset(pre, -1, sizeof(pre)); memset(min_flow, 0, sizeof(min_flow)); queue<int> Q; Q.push(1); min_flow[1] = INF; while (!Q.empty()) { u = Q.front(); Q.pop(); if (u == m) break; for (int i = 2; i <= m; i++) if (pre[i] < 0 && c[u][i] - flow[u][i] > 0) { pre[i] = u; min_flow[i] = min(min_flow[u], c[u][i] - flow[u][i]); Q.push(i); } } if (pre[m] == -1) break; for (int v = m; v != 1; v = pre[v]) { u = pre[v]; flow[u][v] += min_flow[m]; flow[v][u] -= min_flow[m]; } ans += min_flow[m]; } return ans; } int main() { int x, y, z; while (scanf("%d%d", &n, &m) != EOF) { memset(c, 0, sizeof(c)); for (int i = 0; i < n; i++) { scanf("%d%d%d", &x, &y, &z); c[x][y] += z; } printf("%d\n", max_flow()); } return 0; }