有N个岛屿 M条无向路 每个路有一最大允许的客流量,求从最西的那个岛屿最多能运用多少乘客到最东的那个岛屿。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 #define M 410000//边 6 #define N 110000//点 7 using namespace std; 8 #define INF 0x3f3f3f3f 9 struct edge 10 { 11 int from; 12 int to; 13 int c; 14 int next; 15 }edge[M]; 16 int ant,head[N],dep[N],gap[N]; 17 void add(int a,int b,int c) 18 { 19 edge[ant].from=a; 20 edge[ant].to=b; 21 edge[ant].c=c; 22 edge[ant].next=head[a]; 23 head[a]=ant++; 24 edge[ant].from=b; 25 edge[ant].to=a; 26 edge[ant].c=0; 27 edge[ant].next=head[b]; 28 head[b]=ant++; 29 } 30 void BFS(int start,int end) 31 { 32 int i,to,u; 33 memset(dep,-1,sizeof(dep)); 34 memset(gap,0,sizeof(gap)); 35 queue < int > que ; 36 dep[end]=0; 37 gap[0]=1; 38 que.push(end); 39 while(!que.empty()) 40 { 41 u=que.front(); 42 que.pop(); 43 for(i=head[u];i!=-1;i=edge[i].next) 44 { 45 to=edge[i].to; 46 if(dep[to]!=-1||edge[i].c!=0) 47 continue; 48 que.push(to); 49 dep[to]=dep[u]+1; 50 gap[dep[to]]++; 51 } 52 } 53 } 54 int s[N],cur[N],n; 55 int sap(int start,int end) 56 { 57 int res=0; 58 BFS(start,end); 59 int u=start,top=0; 60 memcpy(cur,head,sizeof(head)); 61 while(dep[start]<n) 62 { 63 int i; 64 if(u==end) 65 { 66 int Min=INF,flag; 67 for(i=0;i<top;i++) 68 { 69 if(edge[s[i]].c<Min) 70 { 71 Min=edge[s[i]].c; 72 flag=i; 73 } 74 } 75 res+=Min; 76 for(i=0;i<top;i++) 77 { 78 edge[s[i]].c-=Min; 79 edge[s[i]^1].c+=Min; 80 } 81 top=flag; 82 u=edge[s[top]].from; 83 } 84 if(u!=end&&gap[dep[u]-1]==0)//无增广路 85 break; 86 for(i=cur[u];i!=-1;i=edge[i].next) 87 { 88 if(edge[i].c!=0&&dep[edge[i].to]+1==dep[u]) 89 break; 90 } 91 if(i!=-1) 92 { 93 cur[u]=i; 94 s[top++]=i; 95 u=edge[i].to; 96 } 97 else 98 { 99 int Min=n; 100 for(i=head[u];i!=-1;i=edge[i].next) 101 { 102 if(edge[i].c==0) 103 continue; 104 if(Min>dep[edge[i].to]) 105 { 106 cur[u]=i; 107 Min=dep[edge[i].to]; 108 } 109 } 110 gap[dep[u]]--; 111 dep[u]=Min+1; 112 gap[dep[u]]++; 113 if(u!=start) 114 u=edge[s[--top]].from; 115 } 116 } 117 return res; 118 } 119 int main() 120 { 121 int m,i; 122 int minx,maxx,x,y,start,end,t,c; 123 scanf("%d",&t); 124 while(t--) 125 { 126 minx=INF,maxx=-INF; 127 scanf("%d%d",&n,&m); 128 for(i=1;i<=n;i++) 129 { 130 scanf("%d%d",&x,&y); 131 if(x<=minx) 132 start=i,minx=x; 133 if(x>=maxx) 134 end=i,maxx=x; 135 } 136 ant=0; 137 memset(head,-1,sizeof(head)); 138 for(i=1;i<=m;i++) 139 { 140 scanf("%d%d%d",&x,&y,&c); 141 add(x,y,c); 142 add(y,x,c); 143 } 144 printf("%d\n",sap(start,end)); 145 } 146 return 0; 147 }