Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 13539 | Accepted: 5138 |
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
题意:给你一副无向图,问从1->n->1这样走一个来回所用的最短路径是多少,每条边只能走一次。
分析:最小费用流问题。把边的长度当成费用,每条边容量为1,由于是无向图,所以每条边要处理两次,即u->v,v->u都要加进去。把图建好后跑一遍流量为2的最小费用流得出最小费用即可。
题目链接:http://poj.org/problem?id=2135
代码清单:
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<ctime> #include<cctype> #include<string> #include<cstdio> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> using namespace std; #define end() return 0 typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn = 4000 + 5; const int INF = 0x7f7f7f7f; struct Edge{ int from,to,cap,flow,cost; Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} }; struct MCMF{ int n,m; vector<Edge>edge; //边数的两倍 vector<int>G[maxn]; //邻接表,G[i][j]表示i的第j条边在e数组中的序号 int inq[maxn]; //是否在队列 int d[maxn]; //Bellman-Ford int p[maxn]; //上一条弧 int a[maxn]; //可改进量 void init(int n){ this -> n = n; for(int i=0;i<=n;i++) G[i].clear(); edge.clear(); } void addEdge(int from,int to,int cap,int cost){ edge.push_back(Edge(from,to,cap,0,cost)); edge.push_back(Edge(to,from,0,0,-cost)); m=edge.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BellmanFord(int s,int t,int& flow,int& cost){ memset(d,INF,sizeof(d)); memset(inq,0,sizeof(inq)); d[s]=0; inq[s]=1; p[s]=0; a[s]=INF; queue<int>q; q.push(s); while(!q.empty()){ int u=q.front();q.pop(); inq[u]=0; for(int i=0;i<G[u].size();i++){ Edge& e=edge[G[u][i]]; if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; p[e.to]=G[u][i]; a[e.to]=min(a[u],e.cap-e.flow); if(!inq[e.to]){ q.push(e.to); inq[e.to]=1; } } } } if(d[t]==INF) return false; flow+=a[t]; cost+=d[t]; if(flow==2) return false; for(int u=t;u!=s;u=edge[p[u]].from){ edge[p[u]].flow+=a[t]; edge[p[u]^1].flow-=a[t]; } return true; } //需要保证初始网络中没有负权圈 int MincostMaxflow(int s,int t){ int flow=0,cost=0; while(BellmanFord(s,t,flow,cost)); return cost; } }; int N,M; int a,b,c; MCMF mcmf; void input(){ scanf("%d%d",&N,&M); mcmf.init(N); for(int i=0;i<M;i++){ scanf("%d%d%d",&a,&b,&c); mcmf.addEdge(a,b,1,c); mcmf.addEdge(b,a,1,c); } } void solve(){ printf("%d\n",mcmf.MincostMaxflow(1,N)); } int main(){ input(); solve(); end(); }