hdu 1853

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <cstring>
#include <list>
#include <queue>
#include <stack>
#include <cmath>

using namespace std;

#define PF(x) (scanf("%d",&x))
#define PT(x,y) (scanf("%d%d",&x,&y))
#define PR(x) (printf("%d\n",x))
#define PRT(x,y)(printf("%d %d\n",x,y))
#define PB(x)(scanf("%I64d",&x))
#define PRB(x)(printf("%I64d\n",(x)))
#define For(i,n) for(int i=0;i<(n);i++)
#define CLR(ar) (memset(ar,0,sizeof(ar)))
#define CLR1(ar) (memset(ar,-1,sizeof(ar)))
typedef __int64 LL;
#define N 500
#define M 105
#define Mod 1000
#define Inf 0x7fffffff

int n,m;
int cap[N][N];
int recap[N][N];
int vis[N];
int cost[N][N];
queue<int> G;
int dist[N];
int pre[N];

int mins(int a,int b)
{
	if(a==0) return b;
    return a>b?b:a;
}
bool readata()
{
    if(scanf("%d%d",&n,&m)==EOF) return false;
    CLR(cap);CLR(cost);
    For(i,n)
    {
        cap[0][2*(i+1)] = 1;
    }
    
    For(i,m)
    {
        int x,y,c;
        PT(x,y);PF(c);
        cap[2*x][2*y+1] = 1;
        cost[2*x][2*y+1] = mins(cost[2*x][2*y+1],c);
        cost[2*y+1][2*x] = -mins(cost[2*x][2*y+1],c);
    }
    For(i,n)
    {
        cap[2*(i+1)+1][2*n+2] = 1;
    }
    return true;
}

int bfs(int s,int t,int &x)
{
   while(!G.empty()) G.pop();
    CLR(recap);
    int flow=0,money = 0;

    for(;;)
    {
        For(i,2*n+3) dist[i] = Inf;
        dist[s] = 0;
        memset(vis,0,sizeof(vis));
        G.push(s);

        while(!G.empty())
        {
            int e = G.front(); G.pop();
            vis[e] = 0;
			
            for(int i=0;i<2*n+3;i++)
                if(cap[e][i] >recap[e][i] && dist[i] > dist[e] + cost[e][i])
                {
                    dist[i] = dist[e] + cost[e][i];
                    pre[i] = e;
                    if(!vis[i])
                    {
                        vis[i] = 1;
                        G.push(i);
                    }
                }
        }
        if(dist[t] == Inf) break;
        for(int e = t;e!=s;e = pre[e])
        {
            recap[pre[e]][e] += 1;
            recap[e][pre[e]] -= 1;
        }
        flow += 1;
		money += dist[t]*1;
    }
    x = flow;
    return money;
}
void init()
{
    while(readata())
    {
        int x,y;
        x = 0;
        y = bfs(0,2*n+2,x);
        if(x <n) puts("-1");
        else PR(y);
    }
    return ;
}

int main()
{
    init();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值