1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 6 using namespace std; 7 const int INF=2147483647; 8 const int maxn=210,maxm=410; 9 int cnt,fir[maxn],nxt[maxm],cap[maxm],to[maxm],dis[maxn],gap[maxn],path[maxn]; 10 11 void addedge(int a,int b,int c) 12 { 13 nxt[++cnt]=fir[a]; 14 to[cnt]=b; 15 cap[cnt]=c; 16 fir[a]=cnt; 17 } 18 19 bool BFS(int S,int T) 20 { 21 memset(dis,0,sizeof(dis)); 22 dis[T]=1; 23 queue<int>q;q.push(T); 24 while(!q.empty()) 25 { 26 int node=q.front();q.pop(); 27 for(int i=fir[node];i;i=nxt[i]) 28 { 29 if(dis[to[i]])continue; 30 dis[to[i]]=dis[node]+1; 31 q.push(to[i]); 32 } 33 } 34 return dis[S]; 35 } 36 int fron[maxn]; 37 int ISAP(int S,int T) 38 { 39 if(!BFS(S,T)) 40 return 0; 41 for(int i=1;i<=T;i++)++gap[dis[i]]; 42 int p=S,ret=0; 43 memcpy(fron,fir,sizeof(fir)); 44 while(dis[S]<=T) 45 { 46 if(p==T){ 47 int f=INF; 48 while(p!=S){ 49 f=min(f,cap[path[p]]); 50 p=to[path[p]^1]; 51 } 52 p=T;ret+=f; 53 while(p!=S){ 54 cap[path[p]]-=f; 55 cap[path[p]^1]+=f; 56 p=to[path[p]^1]; 57 } 58 } 59 int &ii=fron[p]; 60 for(;ii;ii=nxt[ii]){ 61 if(!cap[ii]||dis[to[ii]]+1!=dis[p]) 62 continue; 63 else 64 break; 65 } 66 67 if(ii){ 68 p=to[ii]; 69 path[p]=ii; 70 } 71 72 73 else{ 74 if(--gap[dis[p]]==0)break; 75 int minn=T+1; 76 for(int i=fir[p];i;i=nxt[i]) 77 if(cap[i]) 78 minn=min(minn,dis[to[i]]); 79 gap[dis[p]=minn+1]++; 80 fron[p]=fir[p]; 81 if(p!=S) 82 p=to[path[p]^1]; 83 } 84 } 85 return ret; 86 } 87 88 void Init() 89 { 90 memset(fir,0,sizeof(fir)); 91 cnt=1; 92 } 93 int main() 94 { 95 int n,m; 96 while(~scanf("%d%d",&m,&n)) 97 { 98 Init(); 99 for(int i=1;i<=m;i++){ 100 int x,y,c; 101 scanf("%d%d%d",&x,&y,&c); 102 addedge(x,y,c); 103 addedge(y,x,0); 104 } 105 printf("%d\n",ISAP(1,n)); 106 } 107 108 return 0; 109 }
时间: 2024-12-26 16:34:23