HDU 1281 二分图匹配

本文详细解析了HDU-1281二分图匹配问题,通过邻接矩阵实现二分图的最大匹配算法,并判断每条边是否为重要边。使用匈牙利算法求解最大匹配数,再逐条删除边验证其重要性。

HDU - 1281 二分图匹配

这道题用到二分图匹配。

思路的话,因为一个车占一个x和一个y,要它们不能互相攻击,必定一个x只能匹配至多一个y。(同理y也是这样)。

所以我们可以对 x 和 y 进行二分图匹配。

求出最大匹配数目后,一次删一条边,算这种情况下的最大匹配数目有没有发生改变,如果发生了改变,那么必定是重要点,如果没有发生改变那就不是重要点。然后把这条删掉的边再添加回去,一直重复操作直到结束就好了。

个人觉得这道题用邻接矩阵做更顺手。

代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 105;
int n, m, k;
bool G[maxn][maxn];
int match[maxn];
bool used[maxn];
bool dfs(int u){
    for(int i = 1; i <= m; ++i)
    {
        if(G[u][i] && !used[i])
        {
            used[i] = true;
            int w = match[i];
            if(w < 0 || dfs(w))
            {
                match[i] = u;
                return true;
            }
        }
    }
    return false;
}
int Hungary(){
    int ans = 0;
    memset(match, -1, sizeof(match));
    for(int i = 1; i <= n; ++i)
    {
        memset(used, false, sizeof(used));
        if(dfs(i))
            ans++;
    }
    return ans;
}
int main(){
    int board = 1;
    while(scanf("%d %d %d", &n, &m, &k) != EOF)
    {
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                G[i][j] = false;
        int x, y;
        for(int i = 1; i <= k; ++i)
        {
            scanf("%d %d", &x, &y);
            G[x][y] = true;
        }
        int cnt = Hungary();
        int ans = 0;
        for(int i = 1; i <= n; ++i)
        {
            for(int j = 1; j <= m; ++j)
            {
                if(G[i][j])
                {
                    G[i][j] = false;
                    if(Hungary() != cnt)
                    {
                        ans++;
                    }
                    G[i][j] = true;
                }
            }
        }
        printf("Board %d have %d important blanks for %d chessmen.\n", board++, ans, cnt);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值