题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1532
#include <stdio.h> #include <queue> #include <string.h> #include <algorithm> #define INT_MAX (int)1e9 using namespace std; const int N = 207; int network[N][N], pre[N], used[N], flow[N], n, m; //pre存储bfs过程中路径,used确保每次bfs对每个节点只遍历一次,flow辅助求bfs过程中的最小流 queue <int> q; int BFS() { memset(used, 0, sizeof(used)); memset(flow, -1, sizeof(flow)); while (!q.empty()) q.pop(); for (int i = 1; i <= m; i++) pre[i] = i; flow[1] = INT_MAX; q.push(1); while (!q.empty()) { int temp = q.front(); q.pop(); for (int i = 1; i <= m; i++) { if (!used[i] && network[temp][i]) { pre[i] = temp; flow[i] = min(flow[temp], network[temp][i]); used[i] = 1; q.push(i); } } } if (flow[m] == -1) return 0; else return flow[m]; } int edmond_karp() //bfs找到最小流,正向减去最小流,并且反向增加最小流 { int ans = 0, minFlow; while (minFlow = BFS()) { ans += minFlow; int r = m; while (r != 1) { network[r][pre[r]] += minFlow; network[pre[r]][r] -= minFlow; r = pre[r]; } } return ans; } int main() { while (scanf("%d%d", &n, &m) != EOF) { memset(network, 0, sizeof(network)); for (int i = 1; i <= n; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); network[u][v] += w; } int ans = edmond_karp(); printf("%d\n", ans); } return 0; }
时间: 2024-11-10 07:24:36