最小费用最大流模板 POJ2135

代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#define ll long long
#define maxn 2200
#define maxm 301000
using namespace std;
const long long my_inf= 214743647;
struct WLL{
int now[maxn];
long long v[maxm];
int st[maxm],ed[maxm],pre[maxm],tot;
long long cost[maxm];
long long deep[ maxn ];
long long ans,sum;
int S,T;

void init(){
tot=1;
memset(now,0,sizeof(now));
}

void build(int a,int b,int c,int d){
pre[++tot]=now[a];
now[a]=tot;
st[tot]=a;
ed[tot]=b;
v[tot]=c;
cost[tot]=d;
}

void add_edge(int a,int b,int cost){
build(a,b,1,cost);
build(b,a,0,-cost);
}

deque<int> Q;

int last[maxn];
bool vis[maxn];

bool spfa(){
memset( deep , -1 , sizeof(deep) );
memset( vis , 0 ,sizeof( vis ) );
deep[S]=0;
Q.push_back(S);
while (!Q.empty())
    {
        int x=Q.front();
        Q.pop_front();
        for (int p=now[x];p;p=pre[p])
            if (v[p])
            if (  ( deep[ed[p]] <0 ) || ( deep[ ed[p] ] > deep[ x ]+cost[ p ] ) )
            {
                int y=ed[p];
                deep[ y ]=deep[ x ]+cost[p];
                last[ y ]= p;
                if ( !vis[ ed[p] ] )
                    {
                        Q.push_back( ed[p] );
                        vis[ ed[p] ]=1;
                    }
            }
        vis[ x ]=0;
    }
if ( deep[ T ]==-1 )
    return 0;
long long Max=my_inf;
for (int x= T; x!=S ; x = st[ last[ x ] ] )
    {
        int  p=last[ x ];
        Max= min( Max , v[ p ] );
    }
sum+=Max;
for (int x= T; x!=S ; x = st[ last[ x ] ] )
    {
        int  p=last[ x ];
        v[ p ] -= Max;
        v[ p^1]+=Max;
        ans+=Max*cost[ p ];
    }
return 1;
}

void count(int &x,int &y){
    sum=0; ans=0;///sum是最大流, ans是最小费用
    while ( spfa() );
    x=sum,y=ans;
}

}A;
int n,m;

void doit(){
    A.init();
    cin>>n>>m;
    for (int i=1;i<=m;i++)
        {
            int a,b,c;
            cin>>a>>b>>c;
            A.add_edge(a,b,c);
            A.add_edge(b,a,c);
        }
    A.S=n+1,A.T=n+2;
    A.add_edge(A.S,1,0);
    A.add_edge(A.S,1,0);
    A.add_edge(n,A.T,0);
    A.add_edge(n,A.T,0);
    int sum,ans;
    A.count(sum,ans);
    if ( sum!=2 )
        cout<<-1<<endl;
    else
        cout<<ans<<endl;
return ;
}

int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    doit();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值