链接:click here
代码:
#include <bits/stdc++.h> using namespace std; const int N=1e4+5; const int INF=0x3f3f3f3f; struct edge { int from,to,cost; }; vector<edge> G[N];//图的邻接表表示 bool vis[N]; void add_edge(int from,int to,int cost) { G[from].push_back((edge) { to,cost,G[to].size() }); G[to].push_back((edge) { from,0,G[from].size()-1 }); } int dfs(int v,int last,int f) { if(v==last) return f; vis[v]=true; for(int i=0; i<G[v].size(); i++) { edge &e=G[v][i]; if(!vis[e.from]&&e.to>0) { int d=dfs(e.from,last,min(f,e.to)); if(d>0) { e.to-=d; G[e.from][e.cost].to+=d; return d; } } } return 0; } int max_flow(int pre,int last)//源点,汇点 { int flow=0; for(;;) { memset(vis,0,sizeof(vis)); int f=dfs(pre,last,INF); if(f==0) return flow; flow+=f; } return flow; } int main() { int n,m,from,to,cost; while(scanf("%d%d",&n,&m)!=EOF) { memset(G,0,sizeof(G)); for(int i=0; i<n; i++) { scanf("%d%d%d",&from,&to,&cost); add_edge(from,to,cost); } int ans=max_flow(1,m); printf("%d\n",ans); } return 0; }
邻接矩阵
#include <cstdio> #include <vector> #include <iostream> #include <queue> #include <cstring> using namespace std; const int N = 300; const int MAX = 0x3f3f3f3f; int map[N][N]; int flow[N][N]; int a[N],p[N]; int Ford_fulkerson(int s,int t) { queue<int> qq; memset(flow,0,sizeof(flow)); int f=0,u,v; while(1) { memset(a,0,sizeof(a)); a[s]=MAX; qq.push(s); while(!qq.empty()) { u=qq.front();qq.pop(); for(v=1;v<=t;v++) { if(!a[v]&&map[u][v]>flow[u][v])//找到新结点v { p[v]=u;qq.push(v);//记录v的父亲,并加入FIFO队列 a[v]=a[u]<map[u][v]-flow[u][v]?a[u]:map[u][v]-flow[u][v];//a[v]为s-v路径上的最小流量 } } } if(a[t]==0) return f; for(int i=t;i!=s;i=p[i]) { flow[i][p[i]]-=a[t]; flow[p[i]][i]+=a[t]; } f+=a[t]; } } int main() { int n,m; while(~scanf("%d%d",&n,&m)) { memset(map,0,sizeof(map)); for(int i=0;i<n;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); map[x][y]+=z; } printf("%d\n",Ford_fulkerson(1,m)); } }