1. 程式人生 > >洛谷P3376 【模板】網路最大流

洛谷P3376 【模板】網路最大流

題目描述

如題,給出一個網路圖,以及其源點和匯點,求出其網路最大流。

輸入輸出格式

輸入格式:

第一行包含四個正整數N、M、S、T,分別表示點的個數、有向邊的個數、源點序號、匯點序號。

接下來M行每行包含三個正整數ui、vi、wi,表示第i條有向邊從ui出發,到達vi,邊權為wi(即該邊最大流量為wi)

輸出格式:

一行,包含一個正整數,即為該網路的最大流。

輸入輸出樣例

輸入樣例#1: 
4 5 4 3
4 2 30
4 3 20
2 3 20
2 1 30
1 3 40
輸出樣例#1: 
50

說明

時空限制:1000ms,128M

資料規模:

對於30%的資料:N<=10,M<=25

對於70%的資料:N<=200,M<=1000

對於100%的資料:N<=10000,M<=100000

樣例說明:

題目中存在3條路徑:

4-->2-->3,該路線可通過20的流量

4-->3,可通過20的流量

4-->2-->1-->3,可通過10的流量(邊4-->2之前已經耗費了20的流量)

故流量總計20+20+10=50。輸出50。

  1 #include<cstdio>
  2 #include<cstring>
  3
#include<iostream> 4 using namespace std; 5 const int maxn=1e4+10; 6 const int maxm=1e5+10; 7 int n,m,S,T,tot=1; 8 int head[maxn],p[maxn],dis[maxn],q[maxn*2]; 9 bool vis[maxn]; 10 long long read() 11 { 12 long long x=0,f=1; 13 char ch=getchar(); 14 while(ch>'
9'||ch<'0') 15 { 16 if(ch=='-') 17 f=-1; 18 ch=getchar(); 19 } 20 while(ch>='0'&&ch<='9') 21 { 22 x=x*10+ch-'0'; 23 ch=getchar(); 24 } 25 return x*f; 26 } 27 struct node 28 { 29 int v,next,cap,flow; 30 } e[maxm<<1]; 31 void add(int x,int y,int z) 32 { 33 e[++tot]=(node) 34 { 35 y,head[x],z,0 36 }; 37 head[x]=tot; 38 e[++tot]=(node) 39 { 40 x,head[y],0,0 41 }; 42 head[y]=tot; 43 } 44 bool bfs() 45 { 46 int h=0,t=1; 47 memset(dis,-1,sizeof(dis)); 48 dis[S]=0; 49 q[1]=S; 50 while(h!=t) 51 { 52 int x=q[++h]; 53 for(int i=head[x]; i; i=e[i].next) 54 { 55 int v=e[i].v; 56 if(dis[v]==-1&&e[i].cap>e[i].flow) 57 { 58 dis[v]=dis[x]+1; 59 q[++t]=v; 60 } 61 } 62 } 63 return dis[T]!=-1; 64 } 65 int dfs(int x,int f) 66 { 67 if(x==T||!f) 68 return f; 69 int used=0,f1; 70 for(int &i=p[x]; i; i=e[i].next) 71 { 72 if(dis[x]+1==dis[e[i].v]&&(f1=dfs(e[i].v,min(f,e[i].cap-e[i].flow)))>0) 73 { 74 e[i].flow+=f1; 75 e[i^1].flow-=f1; 76 used+=f1; 77 f-=f1; 78 if(!f) 79 break; 80 } 81 } 82 return used; 83 } 84 int dinic() 85 { 86 int ans=0; 87 while(bfs()) 88 { 89 for(int i=1; i<=n; i++) 90 p[i]=head[i]; 91 ans+=dfs(S,0x7fffffff); 92 } 93 return ans; 94 } 95 int main() 96 { 97 n=read(),m=read(),S=read(),T=read(); 98 for(int i=1; i<=m; i++) 99 { 100 int x,y,z; 101 x=read(),y=read(),z=read(); 102 add(x,y,z); 103 } 104 printf("%d",dinic()); 105 return 0; 106 }
View Code