标签:
题目链接:http://poj.org/problem?id=2135
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14821 | Accepted: 5657 |
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
#include <iostream> #include <cstring> #include <cstdio> #include <queue> using namespace std; int sumFlow; const int MAXN = 1010; const int MAXM = 1000200; #define INF 0x3f3f3f3f struct Edge { int u; int v; int cap; int cost; int next; } edge[MAXM<<2]; int NE; int head[MAXN], dist[MAXN], pre[MAXN]; bool vis[MAXN]; void addedge(int u,int v,int cap,int cost) { edge[NE].u=u; edge[NE].v=v; edge[NE].cap=cap; edge[NE].cost=cost; edge[NE].next=head[u]; head[u]=NE++; edge[NE].u=v; ///反的容量图 edge[NE].v=u; edge[NE].cap=0; edge[NE].cost=-cost; edge[NE].next=head[v]; head[v]=NE++; } bool SPFA(int s,int t,int n) { int i,u,v; queue<int>Q; memset(vis,false,sizeof(vis)); memset(pre,-1,sizeof(pre)); for(i=0; i<=n; i++) dist[i]=INF; vis[s]=true; dist[s]=0; Q.push(s); while(!Q.empty()) { u=Q.front(); Q.pop(); vis[u]=false; for(i=head[u]; i!=-1; i=edge[i].next) { v=edge[i].v; if(edge[i].cap&&dist[v]>dist[u]+edge[i].cost) { dist[v]=dist[u]+edge[i].cost; pre[v]=i; if(!vis[v]) { Q.push(v); vis[v]=true; } } } } if(dist[t]==INF) return false; return true; } int MCMF(int s,int t,int n) { int flow=0; /// 总流量 int minflow,mincost; mincost=0; while(SPFA(s,t,n)) { minflow=INF+1; ///容量瓶颈 for(int i=pre[t]; i!=-1; i=pre[edge[i].u]) if(edge[i].cap<minflow) minflow=edge[i].cap; flow+=minflow; for(int i=pre[t]; i!=-1; i=pre[edge[i].u]) { edge[i].cap-=minflow; edge[i^1].cap+=minflow; ///更新残余网络,^1处理,因为0,是正边,1是反边,做^1,就能找到反边 } mincost+=dist[t]*minflow; ///这里和书上有点不一样,就是相当于一个合并同类项了,dist[t]到汇点的最少花费*瓶颈容量 } sumFlow=flow; /// 最大流 return mincost; } int main() { int n,m; int u,v,c; while(~scanf("%d%d",&n,&m)) { NE=0; memset(head,-1,sizeof(head)); int S=0; int T=n+1; while(m--) { scanf("%d%d%d",&u,&v,&c); addedge(u,v,1,c); addedge(v,u,1,c); ///建反图,这样在SPFA里面就能回来了, } addedge(S,1,2,0); addedge(n,T,2,0); int ans=MCMF(S,T,T+1); printf("%d\n",ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/TreeDream/p/5755949.html