【模板】网络流-最大流 Dinic

洛谷 3376

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #define N 10010
 5 #define rg register
 6 using namespace std;
 7 int n,m,S,T,tot,ans,last[N],d[N],q[N],cur[N];
 8 struct edge{
 9     int to,pre,f;
10 }e[200010];
11 inline int read(){
12     int k=0,f=1; char c=getchar();
13     while(c<'0'||c>'9')c=='-'&&(f=-1),c=getchar();
14     while('0'<=c&&c<='9')k=k*10+c-'0',c=getchar();
15     return k*f;
16 }
17 bool bfs(){
18     memset(d,-1,sizeof(d));
19     d[S]=0;
20     int front=0,rear=1; q[front]=S;
21     while(front<rear){
22         int now=q[front++];
23         for(rg int i=last[now],to;i;i=e[i].pre)
24         if(d[to=e[i].to]==-1&&e[i].f) d[to]=d[now]+1,q[rear++]=to;
25     } 
26     return d[T]>=0;
27 }
28 int dfs(int x,int a){
29     if(x==T||a==0) return a;
30     int flow=0,f;
31     for(rg int &i=cur[x],to;i;i=e[i].pre)
32     if(d[to=e[i].to]==d[x]+1&&e[i].f&&(f=dfs(to,min(a,e[i].f)))){
33         e[i].f-=f; e[i^1].f+=f; flow+=f; a-=f;
34         if(!a) break;
35     }
36     return flow;
37 }
38 int dinic(){
39     int ans=0;
40     while(bfs()){
41         for(rg int i=1;i<=n;i++) cur[i]=last[i];
42         ans+=dfs(S,2e9);
43     }
44     return ans;
45 }
46 int main(){
47     n=read(); m=read(); S=read(); T=read(); tot=1;
48     for(rg int i=1;i<=m;i++){
49         int u=read(),v=read();
50         e[++tot]=(edge){v,last[u],read()}; last[u]=tot;
51         e[++tot]=(edge){u,last[v],0}; last[v]=tot;
52     }
53     printf("%d\n",dinic());
54     return 0;
55 }
View Code

 

posted @ 2018-04-24 09:38  Driver_Lao  阅读(229)  评论(0编辑  收藏  举报