Dinic最大流 || Luogu P3376 【模板】网络最大流
题面:【模板】网络最大流
代码:
1 #include<cstring> 2 #include<cstdio> 3 #include<iostream> 4 #define min(a,b) ((a)<(b)?(a):(b)) 5 using namespace std; 6 inline int rd(){ 7 int x=0,f=1;char c=getchar(); 8 while(c<'0'||c>'9'){if(c=='-')f=-1; c=getchar();} 9 while(c>='0'&&c<='9'){x=x*10+c-'0'; c=getchar();} 10 return f*x; 11 } 12 const int maxn=(1e4)+50,maxm=(1e5)+50; 13 int num_edge=-1,edge_head[maxn],N,M,S,T,w,u,v,Q[maxn<<1],f1,f2,Dep[maxn],Cur[maxn]; 14 struct Edge{int to,nx,dis;}edge[maxm<<1]; 15 inline void Add_edge(int from,int to,int dis){ 16 edge[++num_edge].nx=edge_head[from]; 17 edge[num_edge].to=to; 18 edge[num_edge].dis=dis; 19 edge_head[from]=num_edge; 20 return; 21 } 22 inline bool Bfs(){ 23 memset(Dep,0,sizeof(Dep)); 24 Dep[S]=1; 25 f1=f2=1; 26 Q[f2++]=S; 27 while(f1<f2){ 28 int x=Q[f1++]; 29 for(int i=edge_head[x];i!=-1;i=edge[i].nx){ 30 int y=edge[i].to; 31 if(edge[i].dis&&Dep[y]==0){ 32 Dep[y]=Dep[x]+1; 33 Q[f2++]=y; 34 } 35 } 36 } 37 if(Dep[T])return 1; 38 return 0; 39 } 40 inline int Dfs(int x,int fw){ 41 if(x==T)return fw; 42 for(int &i=Cur[x];i!=-1;i=edge[i].nx){ 43 int y=edge[i].to; 44 if(Dep[y]==Dep[x]+1&&edge[i].dis){ 45 int p=Dfs(y,min(fw,edge[i].dis)); 46 if(p>0){ 47 edge[i].dis-=p; 48 edge[i^1].dis+=p; 49 return p; 50 } 51 } 52 } 53 return 0; 54 } 55 inline int Dinic(){ 56 int ans=0; 57 while(Bfs()){ 58 for(int i=1;i<=N;i++)Cur[i]=edge_head[i]; 59 while(int k=Dfs(S,1<<30))ans+=k; 60 } 61 return ans; 62 } 63 int main(){ 64 memset(edge_head,-1,sizeof(edge_head)); 65 N=rd();M=rd();S=rd();T=rd(); 66 for(int i=1;i<=M;i++){ 67 u=rd();v=rd();w=rd(); 68 Add_edge(u,v,w); 69 Add_edge(v,u,0); 70 } 71 printf("%d\n",Dinic()); 72 return 0; 73 }
By:AlenaNuna