http://poj.org/problem?id=2135
题目大意:
从1到n再回来,每条边只能走一次,问最短路。
——————————————————
如果不告诉我是费用流打死不会想这个……
我们把问题简化为1到n跑两遍,然后每条边容量为1,费用为长度。
然后建一个s和t,s到1容量为2,n到t容量为2.
跑费用流。
(注意,本题是双向边~!)
#include<cstdio> #include<iostream> #include<queue> #include<cstring> #include<algorithm> #include<cctype> using namespace std; typedef long long ll; const int INF=1e9; const int maxn=1010; inline int read(){ int X=0,w=0;char ch=0; while(!isdigit(ch)){w|=ch=='-';ch=getchar();} while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar(); return w?-X:X; } struct node{ int nxt; int to; int w; int b; }edge[50010]; int head[maxn],cnt=-1; void add(int u,int v,int w,int b){ cnt++; edge[cnt].to=v; edge[cnt].w=w; edge[cnt].b=b; edge[cnt].nxt=head[u]; head[u]=cnt; return; } int dis[maxn]; bool vis[maxn]; inline bool spfa(int s,int t,int n){ deque<int>q; memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++)dis[i]=INF; dis[t]=0;q.push_back(t);vis[t]=1; while(!q.empty()){ int u=q.front(); q.pop_front();vis[u]=0; for(int i=head[u];i!=-1;i=edge[i].nxt){ int v=edge[i].to; int b=edge[i].b; if(edge[i^1].w&&dis[v]>dis[u]-b){ dis[v]=dis[u]-b; if(!vis[v]){ vis[v]=1; if(!q.empty()&&dis[v]<dis[q.front()]){ q.push_front(v); }else{ q.push_back(v); } } } } } return dis[s]<INF; } int ans=0; int dfs(int u,int flow,int m){ if(u==m){ vis[m]=1; return flow; } int res=0,delta; vis[u]=1; for(int e=head[u];e!=-1;e=edge[e].nxt){ int v=edge[e].to; int b=edge[e].b; if(!vis[v]&&edge[e].w&&dis[u]-b==dis[v]){ delta=dfs(v,min(edge[e].w,flow-res),m); if(delta){ edge[e].w-=delta; edge[e^1].w+=delta; res+=delta; ans+=delta*b; if(res==flow)break; } } } return res; } inline int costflow(int S,int T,int n){ while(spfa(S,T,n)){ do{ memset(vis,0,sizeof(vis)); dfs(S,INF,T); }while(vis[T]); } return ans; } int main(){ memset(head,-1,sizeof(head)); int n=read(); int m=read(); int S=n+1,T=n+2; for(int i=1;i<=m;i++){ int u=read(); int v=read(); int f=read(); add(u,v,1,f); add(v,u,0,-f); add(v,u,1,f); add(u,v,0,-f); } add(S,1,2,0);add(1,S,0,0); add(n,T,2,0);add(T,n,0,0); printf("%d ",costflow(S,T,n+2)); return 0; }