第一次写网络流,edmonds karp 算法
唯一需要注意的是输入中有多重边.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | #include <iostream> #include <queue> #define msize 205 using namespace std; int r[msize][msize]; //残留网络,初始为原图 bool visited[msize]; int pre[msize]; int n,m; //n条边,m个顶点 bool bfs(int s,int t) //寻找一条从s到t的增广路,若找到,返回true { int p; queue<int> Q; memset(pre,-1,sizeof(pre)); memset(visited,false,sizeof(visited)); pre[s]=s; visited[s]=true; Q.push(s); while (!Q.empty()) { p=Q.front(),Q.pop(); for (int i=1;i<=m;i++) { if (r[p][i]>0&&!visited[i]) { pre[i]=p; visited[i]=true; if (i==t) return true; Q.push(i); } } } return false; } int maxFlow(int s,int t) { int flow=0,d; while (bfs(s,t)) { d=INT_MAX; for (int i=t;i!=s;i=pre[i]) d=min(d,r[pre[i]][i]); for (int i=t;i!=s;i=pre[i]) r[pre[i]][i] -= d, r[i][pre[i]] += d; flow += d; } return flow; } int main() { int s,e,c; while (scanf(“%d%d”,&n,&m)==2) { memset(r,0,sizeof(r)); for (int i=0;i<n;i++) { scanf(“%d%d%d”,&s,&e,&c); r[s][e] += c; } printf(“%d\n”,maxFlow(1,m)); } return 0; } |











