【POJ2135】Farm Tour(最小费用最大流)

题目描述

传送门
注意为无向图。

题解

可以把题目转化为求1~n的两条路径,使路程最短。每条边限用一次。
按照题目所给的方式建图,每条边容量为1,费用为它的路径长度;从超级源向1连边,容量为2,费用为0;从n向超级汇连边,容量为2,费用为0。这样就满足了保证有两条路径、并且路径长度最小的要求。
利用最小费用最大流求解。

代码

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int max_n=1005;
const int max_m=20005;
const int max_e=max_m*2;
const int inf=1e9;

int n,m,maxflow,mincost,x,y,z;
int point[max_n],next[max_e],v[max_e],c[max_e],remain[max_e],tot;
int dis[max_n],last[max_n];
bool vis[max_n];
queue <int> q;

inline void clear(){
    tot=-1;
    memset(point,-1,sizeof(point));
    memset(next,-1,sizeof(next));
    memset(v,0,sizeof(v));
    memset(c,0,sizeof(c));
    memset(remain,0,sizeof(remain));
    memset(dis,0,sizeof(dis));
    memset(last,0,sizeof(last));
    memset(vis,0,sizeof(vis));
    maxflow=mincost=x=y=z=0;
    while (!q.empty()) q.pop();
}

inline void addedge(int x,int y,int cap,int z){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z; remain[tot]=cap;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; c[tot]=-z; remain[tot]=0;
}

inline int addflow(int s,int t){
    int ans=inf,now=t;
    while (now!=s){
        ans=min(ans,remain[last[now]]);
        now=v[last[now]^1];
    }

    now=t;
    while (now!=s){
        remain[last[now]]-=ans;
        remain[last[now]^1]+=ans;
        now=v[last[now]^1];
    }
    return ans;
}

inline bool bfs(int s,int t){
    memset(dis,0x7f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    dis[s]=0;
    vis[s]=true;
    while (!q.empty()) q.pop();
    q.push(s);

    while (!q.empty()){
        int now=q.front(); q.pop();
        vis[now]=false;
        for (int i=point[now];i!=-1;i=next[i])
          if (remain[i]&&dis[v[i]]>dis[now]+c[i]){
            dis[v[i]]=dis[now]+c[i];
            last[v[i]]=i;
            if (!vis[v[i]]){
                vis[v[i]]=true;
                q.push(v[i]);
            }
          }
    }
    if (dis[t]>inf) return false;
    int flow=addflow(s,t);
    maxflow+=flow;
    mincost+=flow*dis[t];
    return true;
}

inline void major(int s,int t){
    maxflow=0; mincost=0;
    while (bfs(s,t));
}

int main(){
    while (~scanf("%d%d",&n,&m)){
        clear();

        n+=2;
        for (int i=1;i<=m;++i){
            scanf("%d%d%d",&x,&y,&z);
            addedge(x+1,y+1,1,z);
            addedge(y+1,x+1,1,z);
        }
        addedge(1,2,2,0);
        addedge(n-1,n,2,0);

        major(1,n);
        printf("%d\n",mincost);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值