POJ3068:"Shortest" pair of paths——题解
http://poj.org/problem?id=3068
题目大意:
从0~n-1找到两条边和点都不相同(除了0和n-1外)的最小费用路径。
————————————————————————————
POJ2135魔改版。
按照那题的思路并且把点拆成中间连一条容量为1的边即可。
切了切了。
#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 N=70; const int M=20100; 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[M]; int head[N],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[N]; bool vis[N]; 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){ int flow=0; while(spfa(S,T,n)){ do{ memset(vis,0,sizeof(vis)); flow+=dfs(S,INF,T); }while(vis[T]); } return flow; } void restart(){ memset(head,-1,sizeof(head)); cnt=-1; ans=0; return; } int main(){ int ecnt=0,n,m; while(scanf("%d%d",&n,&m)!=EOF&&n&&m){ restart(); ecnt++; int F=1,E=n; int S=n*2+1,T=S+1; add(S,F,2,0);add(F,S,0,0); add(E,T,2,0);add(T,E,0,0); for(int i=2;i<=n-1;i++){ add(i,i+n,1,0); add(i+n,i,0,0); } for(int i=1;i<=m;i++){ int u=read()+1; int v=read()+1; int b=read(); if(u!=1&&u!=n)u+=n; add(u,v,1,b); add(v,u,0,-b); } int flow=costflow(S,T,T); printf("Instance #%d: ",ecnt); if(flow!=2){ printf("Not possible\n"); }else printf("%d\n",ans); } return 0; }