[poj] 1235 Farm Tour || 最小费用最大流

原题

费用流板子题。
费用流与最大流的区别就是把bfs改为spfa,dfs时把按deep搜索改成按最短路搜索即可

#include<cstdio>
#include<queue>
#include<cstring>
#define N 20020
using namespace std;
int n,m,src, des, head[N],dis[N],cur[N],ans,cnt=2,s,t, ANS;
queue <int> q;
bool vis[N];
struct hhh
{
    int to,next,w,cost;
}edge[500005];

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]=0x3f3f3f3f;
    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]!=0x3f3f3f3f;
}

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;
}

int main()
{
    scanf("%d%d",&n,&m);
    s=0;
    t=n+1;
    for (int i=1,a,b,d;i<=m;i++)
    {
	a=read();
	b=read();
	d=read();
	addEdge(a,b,1,d);
	addEdge(b,a,1,d);
    }
    addEdge(s,1,2,0);
    addEdge(n,t,2,0);
    while (bfs()) ans+=dfs(s,0x3f3f3f3f);
    printf("%d
",ANS);
    return 0;
}
原文地址:https://www.cnblogs.com/mrha/p/7977666.html