原题:http://poj.org/problem?id=1273
题意:有 m 个点,n 条边,求 1 到 m 的最大流,模板题;
#include<cstdio> #include<cstring> #include<string> #include<queue> #include<vector> #include<algorithm> #define inf 0x3f3f3f3f using namespace std; const int maxn = 250; int n, m; struct Edge { int from, to, flow, cap; }edge[maxn*2]; vector<int>G[maxn]; int edgenum; void add(int u, int v, int c) { edge[edgenum].from = u; edge[edgenum].to = v; edge[edgenum].cap = c; edge[edgenum].flow = 0; edgenum++; edge[edgenum].from = v; edge[edgenum].to = u; edge[edgenum].cap = 0; edge[edgenum].flow = 0; edgenum++; G[u].push_back(edgenum-2); G[v].push_back(edgenum-1); } bool vis[maxn]; int deep[maxn]; void BFS(int s, int t) { memset(vis, false, sizeof vis); queue<int>Q; Q.push(t); deep[t] = 0; vis[t] = true; while(!Q.empty()) { int now = Q.front(); Q.pop(); for(int i = 0;i<(int)G[now].size();i++) { int v = edge[G[now][i]].to; if(!vis[v]) { deep[v] = deep[now] + 1; vis[v] = true; Q.push(v); } } } // for(int i = 1;i<=m;i++) // { // printf("%d %d\n", i, deep[i]); // } } int gap[maxn], cur[maxn], front[maxn]; int Augment(int s, int t) { int minflow = inf; int begin = t; while(begin != s) { Edge& e = edge[front[begin]]; minflow = min(minflow, e.cap - e.flow); begin = e.from; } begin = t; while(begin != s) { Edge& e = edge[front[begin]]; e.flow += minflow; edge[front[begin]^1].flow -= minflow; begin = e.from; } return minflow; } int Maxflow(int s, int t) { int flow = 0; BFS(s, t); memset(gap, 0, sizeof gap); memset(cur, 0, sizeof cur); for(int i = 1;i<m;i++) gap[deep[i]]++; int begin = s; while(deep[s] < m) { if(begin == t) { flow += Augment(s, t); begin = s; } bool flag = false; for(int i = cur[begin];i<(int)G[begin].size();i++) { Edge& e = edge[G[begin][i]]; if(e.cap > e.flow && deep[begin] == deep[e.to] + 1) { front[e.to] = G[begin][i]; cur[begin] = i; begin = e.to; flag = true; break; } } if(!flag) { int k = m-1; for(int i = 0;i<(int)G[begin].size();i++) { Edge& e = edge[G[begin][i]]; if(e.cap > e.flow) { k = min(k, deep[e.to]); } } if(--gap[deep[begin]] == 0) break; gap[deep[begin] = k+1]++; cur[begin] = 0; if(begin != s) { begin = edge[front[begin]].from; } } } return flow; } void init() { for(int i = 1;i<=m;i++) G[i].clear(); edgenum = 0; memset(deep, 0, sizeof deep); } int main() { while(~scanf("%d%d", &n, &m)) { init(); while(n--) { int u, v, c; scanf("%d%d%d", &u, &v, &c); add(u, v, c); } int flow = Maxflow(1, m); printf("%d\n", flow); } return 0; }