首页 > 代码库 > POJ2135Farm Tour(最小费用最大流模板)

POJ2135Farm Tour(最小费用最大流模板)

题目链接:http://poj.org/problem?id=2135

题意:农场主想从1到n,然后从n到1,每条边最多走一次,不能走重复的路,问最短距离是多少。

建图:取超级源点s,并与房子连一条边,容量为2,费用为0;取barn与超级汇点 t 的边的容量为2,费用为0

房子与barn的费用为距离,容量为1

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
const int maxn = 3010;
const int maxm = 80000;
const int inf = 1e8;
#define MIN INT_MIN
#define MAX 1e6
#define LL long long
#define init(a) memset(a,0,sizeof(a))
#define FOR(i,a,b) for(int i = a;i<b;i++)
#define max(a,b) (a>b)?(a):(b)
#define min(a,b) (a>b)?(b):(a)
using namespace std;
struct node{
    int u,v,w,cap,next;
}edge[maxm];
int head[maxn],dis[maxn],pre[maxn];
int cnt,n;
bool vis[maxn];
void add(int u,int v,int w,int cap)
{
    edge[cnt].u = u;
    edge[cnt].v = v;
    edge[cnt].w = w;
    edge[cnt].cap = cap;
    edge[cnt].next = head[u];
    head[u] = cnt++;

    edge[cnt].u = v;
    edge[cnt].v = u;
    edge[cnt].w = -w;
    edge[cnt].cap = 0;
    edge[cnt].next = head[v];
    head[v] = cnt++;
}
void initt()
{
    cnt = 0;
    memset(head,-1,sizeof(head));
}
bool SPFA(int s,int t)
{
    queue<int>q;
    while(q.empty()==false) q.pop();

    q.push(s);

    init(vis);
    memset(pre,-1,sizeof(pre));
    
    FOR(i,s,t+1)
    dis[i] = inf;
    vis[s] = 1;
    dis[s] = 0;

    while(!q.empty())
    {
        int uu = q.front();
        q.pop();
        vis[uu] = 0;
        for(int i = head[uu];i!=-1;i = edge[i].next)
        {
            if(edge[i].cap && dis[edge[i].v] > dis[uu] + edge[i].w)//找最小费用
            {
                dis[edge[i].v] = dis[uu] + edge[i].w;
                pre[edge[i].v] = i;//记录路径
                if(!vis[edge[i].v])
                {
                    vis[edge[i].v] = 1;

                q.push(edge[i].v);
                }

            }
        }
    }
    if(dis[t]!=inf)
        return 1;
    return 0;

}
int MinCostMaxFlow(int s,int t)
{
    int flow = 0,cost = 0;//总流量、总费用
    while(SPFA(s,t))
    {
        int df = inf;
        for(int i = pre[t];i!=-1;i=pre[edge[i].u])
        {
            if(df > edge[i].cap)
                df = edge[i].cap;
        }
        flow += df;//这条路径的流量
        for(int i = pre[t];i!=-1;i=pre[edge[i].u])//更新流量
        {
            edge[i].cap -= df;
            edge[i^1].cap += df;
        }
        cost += df*dis[t];//单位费用诚意流量
    }
    return cost;
}
int main()
{
    int u,v,w,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        initt();
        FOR(i,0,m)
        {
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w,1);//无向边,费用w,容量1
            add(v,u,w,1);
        }
        add(0,1,0,2);
        add(n,n+1,0,2);
        int ans = MinCostMaxFlow(0,n+1);
        cout<<ans<<endl;
    }
    return 0;
}