初涉网络流。改日再写一些概念性的介绍。
ek算法可作为模板使用。
#include <iostream>
#include <queue> using namespace std; #define MAXN 105 #define inf 1 << 20 bool used[MAXN]; int pre[MAXN]; int map[MAXN][MAXN]; int vertices, power_stations, consumers, edges; int EK() { int i, res = 0, now, min; queue<int>q; while (1) { memset(pre, -1, sizeof(pre)); memset(used, 0, sizeof(used)); while (!q.empty()) q.pop(); q.push(0); used[0] = true; while (!q.empty()) { now = q.front(); q.pop(); if (now == vertices + 1) break; for (i = 0; i <= vertices + 1; i++) { if (!used[i] && map[now][i]>0) { pre[i] = now; used[i] = true; q.push(i); } } } if (!used[vertices + 1]) break; min = inf; for (i = vertices + 1; i != 0; i = pre[i]) if (map[pre[i]][i]<min) min = map[pre[i]][i]; res = res + min; for (i = vertices + 1; i != 0; i = pre[i]) { map[pre[i]][i] = map[pre[i]][i] - min; map[i][pre[i]] = map[i][pre[i]] + min; } } return res; } int main() { while (cin >> vertices >> power_stations >> consumers >> edges) { memset(map, 0, sizeof(map)); for (int i = 0; i < edges; i++) { char waste; int from, to, capacity; cin >> waste >> from >> waste >> to >> waste >> capacity; map[from+1][to+1] = capacity; } int super_s, super_t; super_s = 0, super_t = vertices + 1; //vertices += 2; for (int i = 0; i < power_stations; i++) { char waste; int to, capacity; cin >> waste >> to >> waste >> capacity; map[super_s][to+1] = capacity; } for (int i = 0; i < consumers; i++) { char waste; int from, capacity; cin >> waste >> from >> waste >> capacity; map[from+1][super_t] = capacity; } cout << EK() << endl; } return 0; } |