[poj] 3068 "Shortest" pair of paths || 最小费用最大流

[原题](http://poj.org/problem?id=3068)

给一个有向带权图,求两条从0-N-1的路径,使它们没有公共点且边权和最小 。
//是不是像传纸条啊~
是否可行只要判断最后最大流是不是2就可以了

#include<cstdio>
#include<queue>
#include<cstring>
#define N 1010*1010
#define inf 0x3f3f3f3f
using namespace std;
int n,m,head[N],dis[N],cur[N],ans,cnt=2,s,t,ANS,T,cse;
queue <int> q;
bool vis[N];
struct hhh
{
    int to,next,w,cost;
}edge[1000005];

int read()
{
    int ans=0,fu=1;
    char j=getchar();
    for (;(j<'0' || j>'9') && j!='-';j=getchar()) ;
    if (j=='-') fu=-1,j=getchar();
    for (;j>='0' && j<='9';j=getchar()) ans*=10,ans+=j-'0';
    return ans*fu;
}

void add(int u,int v,int w,int c)
{
    edge[cnt].to=v;
    edge[cnt].w=w;
    edge[cnt].next=head[u];
    edge[cnt].cost=c;
    head[u]=cnt++;
}

void addEdge(int u,int v,int w,int c)
{
    add(u,v,w,c);
    add(v,u,0,-c);
}

bool bfs()
{
    for (int i=s;i<=t;i++)
	vis[i]=0,cur[i]=head[i],dis[i]=inf;
    q.push(s);
    dis[s]=0;
    vis[s]=1;
    while(!q.empty())
    {
	int r=q.front();
	q.pop();
	vis[r]=0;
	for (int i=head[r],v;i;i=edge[i].next)
	{
	    v=edge[i].to;
	    if (edge[i].w>0 && dis[r]+edge[i].cost<dis[v])
	    {
		dis[v]=dis[r]+edge[i].cost;
		if (!vis[v])
		{
		    vis[v]=1;
		    q.push(v);
		}
	    }
	}
    }
    return dis[t]!=inf;
}

int dfs(int x,int f)
{
    if (x==t) return ANS+=f*dis[t],f;
    int ha=0,now;
    vis[x]=1;
    for (int &i=cur[x],v;i;i=edge[i].next)
    {
	v=edge[i].to;
	if (vis[v]) continue;
	if (edge[i].w>0 && dis[v]==dis[x]+edge[i].cost)
	{
	    now=dfs(v,min(f-ha,edge[i].w));
	    if (now)
	    {
		ha+=now;
		edge[i].w-=now;
		edge[i^1].w+=now;
	    }
	}
	if (ha==f) return ha;
    }
    return ha;
}

void init()
{
    memset(head,0,sizeof(head));
    cnt=2;
    ANS=0;
    ans=0;
}

int main()
{
    while (~scanf("%d%d",&n,&m))
    {
	if (!n && !m) break;
	++cse;
	printf("Instance #%d: ",cse);
	s=0;
	t=n-1;
	init();
	for (int i=1,a,b,c;i<=m;i++)
	{
	    a=read();
	    b=read();
	    c=read();
	    addEdge(a,b,1,c);
	}
	while (bfs()) if (ans==2) break;else ans+=dfs(s,inf);
	if (ans==2) printf("%d
",ANS);
	else printf("Not possible
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mrha/p/7977708.html