标签:
3 7 8 1 2 1 1 3 1 2 4 1 3 4 1 4 5 1 4 6 1 5 7 1 6 7 1 1 7 6 7 1 2 1 2 3 1 1 3 3 3 4 1 3 5 1 4 6 1 5 6 1 1 6 2 2 1 2 1 1 2 2 1 2
2 1 1
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int INF = 0x3f3f3f3f; 4 const int maxn = 1010; 5 struct arc{ 6 int to,w,next; 7 arc(int x = 0,int y = 0,int z = -1){ 8 to = x; 9 w = y; 10 next = z; 11 } 12 }e[1000005]; 13 int head[maxn],hd[maxn],d[maxn],gap[maxn],tot,n,m,S,T; 14 bool in[maxn] = {}; 15 void add(int head[maxn],int u,int v,int wa,int wb){ 16 e[tot] = arc(v,wa,head[u]); 17 head[u] = tot++; 18 e[tot] = arc(u,wb,head[v]); 19 head[v] = tot++; 20 } 21 void spfa(){ 22 queue<int>q; 23 memset(d,0x3f,sizeof d); 24 d[S] = 0; 25 q.push(S); 26 while(!q.empty()){ 27 int u = q.front(); 28 q.pop(); 29 in[u] = false; 30 for(int i = hd[u]; ~i; i = e[i].next){ 31 if(d[e[i].to] > d[u] + e[i].w){ 32 d[e[i].to] = d[u] + e[i].w; 33 if(!in[e[i].to]){ 34 in[e[i].to] = true; 35 q.push(e[i].to); 36 } 37 } 38 } 39 } 40 for(int i = 1; i <= n; ++i){ 41 for(int j = hd[i]; ~j; j = e[j].next){ 42 if(d[e[j].to] == d[i] + e[j].w) 43 add(head,i,e[j].to,1,0); 44 } 45 } 46 } 47 int dfs(int u,int low){ 48 if(u == T) return low; 49 int tmp = 0,minH = n - 1; 50 for(int i = head[u]; ~i; i = e[i].next){ 51 if(e[i].w){ 52 if(d[e[i].to] + 1 == d[u]){ 53 int a = dfs(e[i].to,min(low,e[i].w)); 54 e[i].w -= a; 55 e[i^1].w += a; 56 tmp += a; 57 low -= a; 58 if(!low) break; 59 if(d[S] >= n) return tmp; 60 } 61 if(e[i].w) minH = min(minH,d[e[i].to]); 62 } 63 } 64 if(!tmp){ 65 if(--gap[d[u]] == 0) d[S] = n; 66 ++gap[d[u] = minH + 1]; 67 } 68 return tmp; 69 } 70 void bfs(){ 71 queue<int>q; 72 memset(d,-1,sizeof d); 73 memset(gap,0,sizeof gap); 74 q.push(T); 75 d[T] = 0; 76 while(!q.empty()){ 77 int u = q.front(); 78 q.pop(); 79 ++gap[d[u]]; 80 for(int i = head[u]; ~i; i = e[i].next){ 81 if(d[e[i].to] == -1){ 82 d[e[i].to] = d[u] + 1; 83 q.push(e[i].to); 84 } 85 } 86 } 87 } 88 int sap(int ret = 0){ 89 bfs(); 90 while(d[S] < n) ret += dfs(S,INF); 91 return ret; 92 } 93 int main(){ 94 int kase,u,v,w; 95 scanf("%d",&kase); 96 while(kase--){ 97 scanf("%d%d",&n,&m); 98 memset(head,-1,sizeof head); 99 memset(hd,-1,sizeof hd); 100 for(int i = tot = 0; i < m; ++i){ 101 scanf("%d%d%d",&u,&v,&w); 102 if(u == v) continue; 103 add(hd,u,v,w,INF); 104 } 105 scanf("%d%d",&S,&T); 106 spfa(); 107 printf("%d\n",sap()); 108 } 109 return 0; 110 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4964984.html