标签:flow set clu return max 模版 ring ems iostream
EK算法:
#include<iostream> #include<algorithm> #include<vector> #include<cstring> using namespace std; struct node{ int to,rev,f; }; int read(){ int x=0; char ch=getchar(); while (ch<‘0‘ || ch>‘9‘) ch=getchar(); while (ch>=‘0‘ && ch<=‘9‘){ x=x*10+ch-‘0‘; ch=getchar(); } return x; } const int maxn=10010,inf=99999999; vector<node>map[maxn]; void add_edge(int s,int t,int f){ map[s].push_back((node){t,map[t].size(),f}); map[t].push_back((node){s,map[s].size()-1,0}); } bool book[maxn]; int dfs(int s,int t,int d){ book[s]=1; if(s==t){ return d; } for(int i=0;i<map[s].size();++i){ if(book[map[s][i].to]||map[s][i].f<=0)continue; int k=dfs(map[s][i].to,t,min(d,map[s][i].f)); if(k<=0)continue; map[s][i].f-=k; map[map[s][i].to][map[s][i].rev].f+=k; return k; } return 0; } int max_flow(int s,int t){ int ret=0; while(1){ memset(book,0,sizeof(book)); int k=dfs(s,t,inf); if(!k)break; ret+=k; } return ret; } int main(){ int n,m,s,t; cin>>n>>m>>s>>t; for(int i=1;i<=m;++i){ int s=read(),t=read(),f=read(); add_edge(s,t,f); } cout<<max_flow(s,t); return 0; }
dinic算法:
#include<cstdio> #include<algorithm> #include<vector> #include<cstring> #include<queue> using namespace std; const int maxn=10010,inf=99999999; struct node{ int to,w,rev; }; int iter[maxn],level[maxn],n; vector<node>map[maxn]; void add_edge(int s,int t,int w){ map[s].push_back((node){t,w,map[t].size()}); map[t].push_back((node){s,0,map[s].size()-1}); } int dfs(int s,int t,int k){ if(s==t){ return k; } for(int &i=iter[s];i<map[s].size();++i){ if(level[map[s][i].to]>level[s]&&map[s][i].w>0){ int d=dfs(map[s][i].to,t,min(k,map[s][i].w)); if(d>0){ map[s][i].w-=d; map[map[s][i].to][map[s][i].rev].w+=d; return d; } } } return -1; } void bfs(int s){ memset(level,-1,sizeof(level)); queue<int>q; level[s]=0; q.push(s); while(!q.empty()){ int v=q.front(); q.pop(); for(int i=0;i<map[v].size();++i){ if(level[map[v][i].to]<0&&map[v][i].w>0){ level[map[v][i].to]=level[v]+1; q.push(map[v][i].to); } } } } int max_flow(int s,int t){ int ret=0; for(;;){ bfs(s); if(level[t]<0)break; memset(iter,0,sizeof(iter)); while(1){ int d=dfs(s,t,inf); if(d==-1)break; ret+=d; } } return ret; } int main(){ int m,s,t; scanf("%d%d%d%d",&n,&m,&s,&t); for(int i=1;i<=m;++i){ int s,t,w; scanf("%d%d%d",&s,&t,&w); add_edge(s,t,w); } printf("%d",max_flow(s,t)); return 0; }
标签:flow set clu return max 模版 ring ems iostream
原文地址:http://www.cnblogs.com/lqs6/p/7455258.html