Farm Tour
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 21991 Accepted: 8430
Description
When FJ’s friends visit him on the farm, he likes to show them around. His farm comprises N (1 <= N <= 1000) fields numbered 1…N, the first of which contains his house and the Nth of which contains the big barn. A total M (1 <= M <= 10000) paths that connect the fields in various ways. Each path connects two different fields and has a nonzero length smaller than 35,000.
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
-
Line 1: Two space-separated integers: N and M.
-
Lines 2…M+1: Three space-separated integers that define a path: The starting field, the end field, and the path’s length.
Output
A single line containing the length of the shortest tour.
Sample Input
4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2
Sample Output
6
费用流的板子题,因为每条路只能走一次,限流为1即可。
然后走到终点再走回来,实际上就是走两次。
为什么会做这道题呢?(比赛之前,测一测 zkw 费用流),防止EK的费用流被卡。
AC代码:
#pragma GCC optimize(2)
#include<queue>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
//#define int long long
using namespace std;
const int inf=0x3f3f3f3f;
const int N=2e3+10,M=2e5+10;
int n,m,s,t,d[N],vis[N],res,st[N];
int head[N],nex[M],to[M],w[M],flow[M],tot=1;
inline void ade(int a,int b,int c,int d){
to[++tot]=b; nex[tot]=head[a]; flow[tot]=c; w[tot]=d; head[a]=tot;
}
inline void add(int a,int b,int c,int d){ade(a,b,c,d); ade(b,a,0,-d);}
inline int spfa(){
memset(st,0,sizeof st); queue<int> q; q.push(s);
memset(d,0x3f,sizeof d); d[s]=0; vis[s]=1;
while(q.size()){
int u=q.front(); q.pop(); vis[u]=0;
for(int i=head[u];i;i=nex[i]){
if(flow[i]&&d[to[i]]>d[u]+w[i]){
d[to[i]]=d[u]+w[i];
if(!vis[to[i]]) vis[to[i]]=1,q.push(to[i]);
}
}
}
return d[t]<inf;
}
int dfs(int x,int f){
if(x==t) return res+=f*d[t],f;
st[x]=1; int fl=0;
for(int i=head[x];i&&f;i=nex[i]){
if(flow[i]&&!st[to[i]]&&d[to[i]]==d[x]+w[i]){
int mi=dfs(to[i],min(flow[i],f));
flow[i]-=mi; flow[i^1]+=mi; fl+=mi; f-=mi;
}
}
return fl;
}
inline int zkw(){
while(spfa()) dfs(s,inf); return res;
}
signed main(){
cin>>n>>m; s=n+1; t=s+1;
for(int i=1,a,b,c;i<=m;i++)
scanf("%d %d %d",&a,&b,&c),add(a,b,1,c),add(b,a,1,c);
add(s,1,2,0); add(n,t,2,0);
cout<<zkw()<<endl;
return 0;
}