题意:给出一个带有n个节点的带权无向图,找到从起点1到终点n的最短往返路,不能重复走同一条边。
思路:引出一条源点S连接到起点,费用为0,流量为2,再从终点连接到汇点T,费用为0,流量为2,然后把题目给出的边的流量设为1,费用设为边权,方向为双向,然后从S到T的最小费用流就是最短往返路,如果总流量不等于2,说明没有往返路。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn=105;
const int inf=1e8;
struct Edge
{
int from,to,cap,flow,cost;
};
struct MCMF
{
int n,m,s,t;
vector<Edge>edges;
vector<int>G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n)
{
this->n=n;
for(int i=0;i<n;i++)G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int cap,int cost)
{
edges.push_back((Edge){from,to,cap,0,cost});
edges.push_back((Edge){to,from,0,0,-cost});
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool Bellmanford(int s,int t,int& flow,int& cost)
{
for(int i=0;i<n;i++)d[i]=inf;
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=edges[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]*a[t];
int u=t;
while(u!=s)
{
edges[p[u]].flow+=a[t];
edges[p[u]^1].flow-=a[t];
u=edges[p[u]].from;
}
return true;
}
int Maxcost(int s,int t)
{
int flow=0,cost=0;
while(Bellmanford(s,t,flow,cost));
if(flow==2)
printf("%d\n",cost);
else
printf("Back to jail\n");
}
}solver;
int main()
{
int n,m,u,v,w;
while(~scanf("%d",&n)&&n)
{
solver.init(n+2);
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
solver.AddEdge(u,v,1,w);
solver.AddEdge(v,u,1,w);
}
solver.AddEdge(0,1,2,0);
solver.AddEdge(n,n+1,2,0);
solver.Maxcost(0,n+1);
}
}