最小费用最大流

namespace MincostMaxflow{
    int head[N],arnum=1;
    struct Arc{int next,to,cap,cost;}arc[M];
    void add(int from,int to,int cap,int cost){
        arc[++arnum].next=head[from];
        head[from]=arnum;
        arc[arnum].to=to;
        arc[arnum].cap=cap;
        arc[arnum].cost=cost;
    }
    void insert(int from,int to,int cap,int cost){add(from,to,cap,cost);add(to,from,0,-cost);}
    int dis[N],pre[N],way[N],book[N];
    int st,en;
    deque<int>Q;
    long long Mincost,Maxflow;
    bool SPFA()
    {
        for(int i=0;i<=N-1;i++)dis[i]=inf;
        memset(pre,0,sizeof(pre));
        memset(way,0,sizeof(way));
        memset(book,0,sizeof(book));
        Q.clear();
        book[st]=1;dis[st]=0;
        Q.push_back(st);
        while(!Q.empty())
        {
            int u=Q.front();book[u]=0;
            Q.pop_front();
            for(int i=head[u];i;i=arc[i].next)
            {
                int v=arc[i].to;
                int cap=arc[i].cap;
                if(cap>0&&dis[v]>dis[u]+arc[i].cost)
                {
                    dis[v]=dis[u]+arc[i].cost;
                    way[v]=u;
                    pre[v]=i;
                    if(!book[v])
                    {
                        book[v]=1;
                        if(Q.empty()||dis[v]>dis[Q.front()])Q.push_back(v);
                        else Q.push_front(v);
                        
                    }
                }
            }
        }
        if(dis[en]==inf)return false;
        int minn=inf;
        for(int i=en;i!=st;i=way[i])
            minn=min(minn,arc[pre[i]].cap);
        Maxflow+=minn;
        Mincost+=minn*dis[en];
        for(int i=en;i!=st;i=way[i])
        {
            arc[pre[i]].cap-=minn;
            arc[pre[i]^1].cap+=minn;
        }
        return true;
    }
}

 

posted @ 2017-10-08 09:17  star_eternal  阅读(167)  评论(0编辑  收藏  举报