HDU 3435 A new Graph Game KM算法

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3435

和HDU 1853 3488代码基本一样

#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <vector>
#include <cmath>
using namespace std;

const int N = 1010;
const int INF = 0x3f3f3f3f;
int n, nx, ny;
int lx[N], ly[N], slack[N], match[N], s[N][N];
bool visx[N], visy[N];

bool hungary(int v)
{
    visx[v] = true;
    for(int i = 1; i <= ny; i++)
    {
        if(visy[i]) continue;
        if(lx[v] + ly[i] == s[v][i])
        {
            visy[i] = true;
            if(match[i] == -1 || hungary(match[i]))
            {
                match[i] = v;
                return true;
            }
        }
        else slack[i] = min(slack[i], lx[v] + ly[i] - s[v][i]);
    }

    return false;
}

void km()
{
    memset(match, -1, sizeof match);
    memset(ly, 0, sizeof ly);
    for(int i = 1; i <= nx; i++)
        lx[i] = -INF;
    for(int i = 1; i <= nx; i++)
        for(int j = 1; j <= ny; j++)
            lx[i] = max(lx[i], s[i][j]);
    for(int i = 1; i <= nx; i++)
    {
        memset(slack, 0x3f, sizeof slack);
        while(true)
        {
            memset(visx, 0, sizeof visx);
            memset(visy, 0, sizeof visy);
            if(hungary(i)) break;
            else
            {
                int d = INF;
                for(int j = 1; j <= ny; j++)
                    if(!visy[j]) d = min(d, slack[j]);
                for(int j = 1; j <= nx; j++)
                    if(visx[j]) lx[j] -= d;
                for(int j = 1; j <= ny; j++)
                    if(visy[j]) ly[j] += d;
                    else slack[j] -= d;
            }
        }
    }
}

int main()
{
    int t, n, m, x = 0;
    int a, b, c;

    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                s[i][j] = -INF;
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d%d", &a, &b, &c);
            if(s[a][b] < -c)
                s[a][b] = s[b][a] = -c;
        }

        nx = n, ny = n;
        km();

        int res = 0;
        bool f = true;
        for(int i = 1; i <= ny; i++)
        {
            if(match[i] == -1 || s[match[i]][i] == -INF)
            {
                f = false; break;
            }
            else res += s[match[i]][i];
        }

        if(f) printf("Case %d: %d\n", ++x, -res);
        else printf("Case %d: NO\n", ++x);
    }

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值