UVA 1658 - Admiral(最小费用流+拆点)

题目链接 https://cn.vjudge.net/problem/UVA-1658

【题意】
给出v (v<=1000) 个点和e (e<=10000)条边的有向图,求1~v的两条不相交(除了起点终点外没有公共点)的路径,使得权和最小。

【思路】
将一个结点拆成两个结点,由真结点连一条容量为1费用为0的边到假结点,这样之后当我们加边的时候,令起始结点为假结点,终止点为真结点。这样就将这个结点隐性的增加了一个容量属性 。 当然,由于我们要经过起始点和末点两次,所以只能将2~n-1号结点拆点,1和n要特殊处理一下。如果是1或n为边的起点,那么就不要用假结点了。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;

const int inf=2e9;
const int maxn=2005;

struct Edge{
    int from,to,cap,flow,cost;
    Edge(int u,int v,int c,int f,int co):from(u),to(v),cap(c),flow(f),cost(co){}
};

struct MCMF{
    int n,m,s,t;
    vector<Edge> edges;
    vector<int> g[maxn];
    int inq[maxn];  
    int d[maxn];    
    int p[maxn];    
    int a[maxn];    

    void init(int n){
        this->n=n;
        for(int i=0;i<n;++i) g[i].clear();
        edges.clear();
    }

    void add(int from,int to,int cap,int cost){
        edges.push_back(Edge(from,to,cap,0,cost));
        edges.push_back(Edge(to,from,0,0,-cost));
        m=edges.size();
        g[from].push_back(m-2);
        g[to].push_back(m-1);
    }

    bool BellmanFord(int s,int t,int& flow,long long& cost){
        for(int i=0;i<n;++i) d[i]=inf;
        memset(inq,0,sizeof(inq));
        d[s]=0;
        inq[s]=1;
        p[s]=0;
        a[s]=inf;

        queue<int> que;
        que.push(s);
        while(!que.empty()){
            int u=que.front();
            que.pop();
            inq[u]=0;
            for(int i=0;i<g[u].size();++i){
                Edge& e=edges[g[u][i]];
                if(e.cap>e.flow && d[e.to]>d[u]+e.cost){
                    d[e.to]=d[u]+e.cost;
                    p[e.to]=g[u][i];
                    a[e.to]=min(a[u],e.cap-e.flow);
                    if(!inq[e.to]){ que.push(e.to);inq[e.to]=1; }
                }
            }
        }
        if(d[t]==inf) return false;
        flow+=a[t];
        cost+=(long long)d[t]*(long long)a[t];
        for(int u=t;u!=s;u=edges[p[u]].from){
            edges[p[u]].flow+=a[t];
            edges[p[u]^1].flow-=a[t];
        }
        return true;
    }

    int MincostMaxflow(int s,int t,long long& cost){
        int flow=0;
        cost=0;
        while(BellmanFord(s,t,flow,cost));
        return cost;
    }
};

int n,m;
MCMF mcmf;

int main(){
    while(scanf("%d%d",&n,&m)==2){
        mcmf.init(maxn-1);
        for(int u=2;u<n;++u){
            mcmf.add(u,u+n,1,0);
        }
        for(int i=0;i<m;++i){
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            if(u!=1 && u!=n) u+=n;
            mcmf.add(u,v,1,w);
        }
        mcmf.add(0,1,2,0);
        mcmf.add(n,n+1,2,0);
        long long ans;
        mcmf.MincostMaxflow(0,n+1,ans);
        printf("%lld\n",ans);
    }
    return 0;
}
posted @ 2018-08-20 11:28  不想吃WA的咸鱼  阅读(83)  评论(0编辑  收藏  举报