POJ-3068-"Shortest" pair of paths
2014-08-20 08:40
351 查看
这个题要求求出0到n-1点的最短的没有任何相同边的最短路径(重复边被认为是不同的边)。
思路:这个题用最小费用流可以解决,首先把所有点的编号+1,然后添加源点0,汇点n+1,然后源点和起始点1连一条容量为2,费用为0的边。同理终点n向汇点连一条费用为0,容量为2的边,然后对于所给的每条边,连一条容量为1,费用为边权的边,然后就跑最小费用流 了
代码:
思路:这个题用最小费用流可以解决,首先把所有点的编号+1,然后添加源点0,汇点n+1,然后源点和起始点1连一条容量为2,费用为0的边。同理终点n向汇点连一条费用为0,容量为2的边,然后对于所给的每条边,连一条容量为1,费用为边权的边,然后就跑最小费用流 了
代码:
#include<cstdio> #include<cstring> #include<iostream> #include<queue> using namespace std; const int inf=1<<29; const int maxn=70; const int maxm=2e4+100; int e,st,des,head[maxn],pnt[maxm],nxt[maxm],cost[maxm],flow[maxm],dist[maxn],pre[maxn]; int n,m; bool vis[maxn]; queue<int> q; void AddEdge(int u,int v,int c,int f) { pnt[e]=v;nxt[e]=head[u];cost[e]=c;flow[e]=f;head[u]=e++; pnt[e]=u;nxt[e]=head[v];cost[e]=-c;flow[e]=0;head[v]=e++; } bool Spfa(int st,int des) { for(int i=0;i<=des;i++) { dist[i]=inf; pre[i]=-1; } dist[st]=0; q.push(st); while(!q.empty()) { int u=q.front(); vis[u]=0; q.pop(); for(int i=head[u];i!=-1;i=nxt[i]) if(flow[i]&&dist[pnt[i]]>dist[u]+cost[i]) { dist[pnt[i]]=dist[u]+cost[i]; pre[pnt[i]]=i; if(!vis[pnt[i]]) { q.push(pnt[i]); vis[pnt[i]]=1; } } } return dist[des]!=inf; } int mincostflow() { int f=0,ans=0; while(Spfa(st,des)) { int mini=inf; for(int i=pre[des];i!=-1;i=pre[pnt[i^1]]) mini=min(mini,flow[i]); for(int i=pre[des];i!=-1;i=pre[pnt[i^1]]) { flow[i]-=mini; flow[i^1]+=mini; } f+=mini; ans+=mini*dist[des]; } if(f<2) return -1; return ans; } int main() { int cas=1; while(scanf("%d%d",&n,&m)&&(n+m)) { st=e=0;des=n+1; memset(head,-1,sizeof(head)); for(int i=0;i<m;i++) { int u,v,c; scanf("%d%d%d",&u,&v,&c); u++;v++; AddEdge(u,v,c,1); } AddEdge(st,1,0,2); AddEdge(n,des,0,2); int ans=mincostflow(); printf("Instance #%d: ",cas++); if(ans==-1) printf("Not possible\n"); else printf("%d\n",ans); } return 0; }
相关文章推荐
- "Shortest" pair of paths - POJ 3068 费用流
- POJ 3068 "Shortest" pair of paths(最小费用最大流-mcmf)
- [poj] 3068 "Shortest" pair of paths || 最小费用最大流
- POJ 3068 "Shortest" pair of paths | 最小费用最大流
- POJ 3068 "Shortest" pair of paths 已翻译
- Poj 3068 "Shortest" pair of paths【拆点+最小费用最大流】
- poj 3068 "Shortest" pair of paths
- poj 3068 "Shortest" pair of paths
- POJ 3068 "Shortest" pair of paths(费用流)
- poj 3068 "Shortest" pair of paths(最小费用流)
- POJ_3068_Shortest_pair_of_paths_(最小费用流)
- poj3068 "Shortest" pair of paths 费用流
- POJ3068 "Shortest" pair of paths
- POJ3068--"Shortest" pair of paths(最小费用流)
- POJ3068:"Shortest" pair of paths——题解
- UVALIVE 2927 "Shortest" pair of paths
- POJ3068: "Shortest" pair of paths 题解
- 通过 composition模拟 "has-a"或 "is-implemented-in-terms-of"
- Java mail包出现"MimeMessage contains object of type javax.mail.util.SharedByteArrayInputStream instead of MimeMultipart"错误的修正办法
- Renderer of "class-based" or "column-based"