跑最小费用流就行了, 建立源点和汇点,源点向1点建费用为0流量为2的边,N点向汇点建立费用为0流量为2的边,然后就模板了
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int inf=1<<29;
const int maxn=110;
const int maxm=maxn*maxn;
int e,m,n,st,des,head[maxn],pnt[maxm],nxt[maxm],cost[maxm],flow[maxm],dist[maxn],pre[maxn];
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()
{
for(int i=st;i<=des;i++)
{
pre[i]=-1;
dist[i]=inf;
}
dist[st]=0;
q.push(st);
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=0;
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 maxflow()
{
int ans=0,cnt=0;
while(Spfa())
{
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;
}
ans+=mini*dist[des];
cnt+=mini;
}
if(cnt==1)
return -1;
return ans;
}
int main()
{
while(scanf("%d",&n)&&n)
{
e=st=0;des=n+1;
memset(head,-1,sizeof(head));
scanf("%d",&m);
for(int i=0;i<m;i++)
{
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
AddEdge(u,v,c,1);
AddEdge(v,u,c,1);
}
AddEdge(st,1,0,2);
AddEdge(n,des,0,2);
int ans=maxflow();
if(ans==-1)
printf("Back to jail\n");
else
printf("%d\n",ans);
}
return 0;
}