1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 #define MP make_pair 6 #define PB push_back 7 #define ls first 8 #define rs second 9 typedef long long LL; 10 typedef pair<int,int> PII; 11 const double eps=1e-8; 12 const double pi=acos(-1.0); 13 const int K=1e5+7; 14 const int mod=1e9+7; 15 16 vector<pair<int,int>>mp[K]; 17 int n,m,cnt,flow[K*2],deep[K],cur[K]; 18 19 int bfs(int s,int t) 20 { 21 queue<int>q; 22 memset(deep,0,sizeof deep); 23 q.push(s),deep[s]=1; 24 while(!q.empty()) 25 { 26 int u=q.front();q.pop(); 27 for(auto &it:mp[u]) 28 if(!deep[it.ls]&&flow[it.rs]) 29 { 30 deep[it.ls]=deep[u]+1; 31 q.push(it.ls); 32 if(it.ls==t) 33 return 1; 34 } 35 } 36 return 0; 37 } 38 int dfs(int x,int d,int t) 39 { 40 if(x==t) return d; 41 for(int i=cur[x];i<mp[x].size();cur[x]=++i) 42 { 43 int u=mp[x][i].ls,v=mp[x][i].rs; 44 if(deep[u]==deep[x]+1&&flow[v]) 45 { 46 int td=min(d,dfs(u,min(d,flow[v]),t)); 47 if(!td) continue; 48 flow[v]-=td; 49 flow[v^1]+=td; 50 return td; 51 } 52 } 53 return 0; 54 } 55 int dinic(int s,int t) 56 { 57 int ret=0,d; 58 while(bfs(s,t)) 59 { 60 memset(cur,0,sizeof cur); 61 while(d=dfs(s,mod,t)) ret+=d; 62 } 63 return ret; 64 } 65 int main(void) 66 { 67 while(~scanf("%d%d",&m,&n)) 68 { 69 cnt=0; 70 memset(mp,0,sizeof mp); 71 for(int i=0,u,v,w;i<m;i++) 72 { 73 scanf("%d%d%d",&u,&v,&w); 74 flow[cnt]=w,flow[cnt+1]=0; 75 mp[u].PB(MP(v,cnt++)); 76 mp[v].PB(MP(u,cnt++)); 77 } 78 printf("%d\n",dinic(1,n)); 79 } 80 return 0; 81 }
原文地址:https://www.cnblogs.com/weeping/p/8783485.html
时间: 2024-10-08 04:25:18