Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14817 | Accepted: 5654 |
Description
To show off his farm in the best way, he walks a tour that starts at his house, potentially travels through some fields, and ends at the barn. Later, he returns (potentially through some fields) back to his house again.
He wants his tour to be as short as possible, however he doesn't want to walk on any given path more than once. Calculate the shortest tour possible. FJ is sure that some tour exists for any given farm.
Input
* Lines 2..M+1: Three space-separated integers that define a path: The starting field, the end field, and the path's length.
Output
Sample Input
4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2
Sample Output
6
Source
给出一个无向图,其中有n个点,m条边,要从1号区域走到n号区域,去的时候和回来的时候不能走一条重复的边。问这一去一回的最小花费。
思路:
1、学习了Min_Cost_Max_flow相关问题,其实想想也不难,只不过是在有流需要处理的一个有向图上的最短路问题。
2、首先是建边。因为是无向图,所以:
那么一去一回,其实可以考虑为两次去。
①每一次加入的边,都要双向建立,费用流沿用了最大流中的退回边,正向边建立的费用是w.退回边建立的费用是-w。因为要求的是每一条边只经过一次不重复,那么其流量限制就是1.
②建立S源点连入1号节点,没有花费,流量为2。表示要去两次N号节点。
②建立T汇点,从N号节点连入,同样没有花费,流量为2,表示要走到N号节点两次。
3、建完图就是跑连续增广路算法--------求最小花费最大流。
理解一下,其实跑连续增广路算法就是在跑很多次SPFA,然后在其基础上处理流量问题。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node
{
int from;
int to;
int w;
int f;
int next;
int num;
}e[15151515];
int n,m,ss,tt,cont;
int path[151515];
int pre[151515];
int head[151515];
int dis[151515];
int vis[151515];
void add(int from,int to,int w,int f)
{
e[cont].from=from;
e[cont].to=to;
e[cont].f=f;
e[cont].w=w;
e[cont].num=cont;
e[cont].next=head[from];
head[from]=cont++;
}
int SPFA()
{
queue<int >s;
s.push(ss);
memset(pre,-1,sizeof(pre));
memset(path,-1,sizeof(path));
for(int i=1;i<=tt;i++)dis[i]=0x3f3f3f3f;
dis[ss]=0;
memset(vis,0,sizeof(vis));
vis[ss]=1;
while(!s.empty())
{
int u=s.front();
s.pop();
vis[u]=0;
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
int w=e[i].w;
int f=e[i].f;
if(f&&dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
pre[v]=u;
path[v]=e[i].num;
if(vis[v]==0)
{
s.push(v);
vis[v]=1;
}
}
}
}
if(dis[tt]!=0x3f3f3f3f)return 1;
else return 0;
}
void Min_costflow()
{
int ans=0;
int maxflow=0;
while(SPFA()==1)
{
int minn=0x3f3f3f3f;
for(int i=tt;i!=ss;i=pre[i])
{
minn=min(minn,e[path[i]].f);
}
maxflow+=minn;
ans+=dis[tt]*minn;
for(int i=tt;i!=ss;i=pre[i])
{
e[path[i]].f-=minn;
e[path[i]^1].f+=minn;
}
}
printf("%d\n",ans);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
ss=n+1;
tt=ss+1;
cont=0;
memset(head,-1,sizeof(head));
for(int i=0;i<m;i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
add(x,y,w,1);
add(y,x,-w,0);
add(y,x,w,1);
add(x,y,-w,0);
}
add(ss,1,0,2);
add(1,ss,0,0);
add(n,tt,0,2);
add(tt,n,0,0);
Min_costflow();
}
}