标签:
Description
Input
Output
Sample Input
4 5 1 2 1 2 3 1 3 4 1 1 3 2 2 4 2
Sample Output
6
Source
1 #include <stdio.h> 2 #include <string.h> 3 #include <queue> 4 using namespace std; 5 const int B=50010; 6 int tot, head[B], next[B], flow[B], w[B], to[B], d[B], S, T, pre[B], bi[B], oq[B]; 7 bool vis[B]; 8 int n,m; 9 queue<int> q; 10 inline void add(int u,int v,int _w,int _flow) { 11 to[tot]=v; flow[tot]=_flow; w[tot]=_w; next[tot]=head[u]; head[u]=tot++; 12 to[tot]=u; flow[tot]=0; w[tot]=-_w; next[tot]=head[v]; head[v]=tot++; 13 } 14 inline int spfa() { 15 memset(d,0x3f3f3f3f,sizeof(d)); 16 memset(oq,0,sizeof(oq)); 17 memset(vis,0,sizeof(vis)); 18 memset(pre,-1,sizeof(pre)); 19 memset(bi,0,sizeof(bi)); 20 while(!q.empty()) q.pop(); 21 d[S]=0; 22 vis[S]=1; 23 pre[S]=S; 24 q.push(S); 25 while(!q.empty()) { 26 int top=q.front(); 27 q.pop(); 28 vis[top]=0; 29 oq[top]++; 30 if(oq[top]>n+2) return -1; 31 for (int i=head[top];i!=-1;i=next[i]) 32 if(flow[i]&&d[top]+w[i]<d[to[i]]) { 33 d[to[i]]=d[top]+w[i]; 34 if(!vis[to[i]]) { 35 vis[to[i]]=1; 36 q.push(to[i]); 37 } 38 pre[to[i]]=top; 39 bi[to[i]]=i; 40 } 41 } 42 if(d[T]==0x3f3f3f3f) return -1; 43 else return d[T]; 44 } 45 inline int mincostflow(int S,int T) { 46 int flowx, cost; 47 flowx=cost=0; 48 while(1) { 49 int minf=0x3f3f3f3f; 50 int Spfa = spfa(); 51 if (Spfa==-1||Spfa==0x3f3f3f3f) break; 52 for (int i=T;i!=S;i=pre[i]) 53 if (flow[bi[i]]<minf) minf=flow[bi[i]]; 54 flowx += minf; 55 cost += Spfa*minf; 56 for (int i=T;i!=S;i=pre[i]) { 57 flow[bi[i]]-=minf; 58 flow[bi[i]^1]+=minf; 59 } 60 //printf("--%d %d\n",flowx,cost); 61 } 62 return cost; 63 } 64 65 int main() { 66 memset(head,-1,sizeof(head)); 67 scanf("%d%d",&n,&m); 68 for (int i=1;i<=m;++i) { 69 int _u,_v,_w; 70 scanf("%d%d%d",&_u,&_v,&_w); 71 add(_u,_v,_w,1); 72 add(_v,_u,_w,1); 73 } 74 // 添加源和汇 75 S=0, T=n+1; 76 add(S,1,0,2); 77 add(n,T,0,2); 78 printf("%d\n",mincostflow(S,T)); 79 return 0; 80 }
标签:
原文地址:http://www.cnblogs.com/TonyNeal/p/poj2135.html