HDU-3829(最大独立集)

本文探讨了如何通过最大匹配算法解决最大独立集问题,具体分析了一道编程竞赛题目,利用匈牙利算法求解使最多人数满意的动物移除方案。文章详细介绍了算法实现过程,包括顶点数与最大匹配数的关系,以及匈牙利算法的具体应用。

题目:HDU - 3829 

The zoo have N cats and M dogs, today there are P children visiting the zoo, each child has a like-animal and a dislike-animal, if the child's like-animal is a cat, then his/hers dislike-animal must be a dog, and vice versa. 
Now the zoo administrator is removing some animals, if one child's like-animal is not removed and his/hers dislike-animal is removed, he/she will be happy. So the administrator wants to know which animals he should remove to make maximum number of happy children. 

Input

The input file contains multiple test cases, for each case, the first line contains three integers N <= 100, M <= 100 and P <= 500. 
Next P lines, each line contains a child's like-animal and dislike-animal, C for cat and D for dog. (See sample for details) 

Output

For each case, output a single integer: the maximum number of happy children.

Sample Input

1 1 2
C1 D1
D1 C1

1 2 4
C1 D1
C1 D1
C1 D2
D2 C1

Sample Output

1
3


        
  

Hint

Case 2: Remove D1 and D2, that makes child 1, 2, 3 happy.
        

 

 

题意:p个人,有n只猫,m条狗,每个人都有自己喜欢的动物额不喜欢的动物,如果挪走不喜欢的,没挪走喜欢的,这个人就会高兴,求求怎样能让高兴的人最多。

分析:

如果AB两个人都高兴,就说明两个人没矛盾,如果A喜欢的不是B讨厌的,A讨厌的不是B喜欢的,就说明两个人是独立的,那这道题就是求最大独立集,最大独立集 = 顶点数 - 最大匹配数

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;


const int maxn = 510;
const int maxm = 2510;
int un,vn;
int g[maxm][maxm];
int linker[maxn];
bool used[maxn];
int n;
int m;
bool dfs(int u)
{
    for(int v = 1;v <= vn;v ++)
    {
        if(g[u][v] && !used[v])
        {
            used[v] = true;
            if(linker[v] == -1 || dfs(linker[v]))
            {
                linker[v] = u;
                return true;
            }
        }
    }
    return false;
}

int hungary()
{
    int res = 0;
    memset(linker,-1,sizeof(linker));
    for(int u = 1;u <= un;u ++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u)) res ++;
    }
    return res;
}

int main()
{
    int p;
    char s1[maxn][10];
    char s2[maxn][10];
    while(cin >> n >> m >> p )
    {
        memset(g,0,sizeof(g));
        for(int i = 0;i < p;i ++)
        {
            scanf("%s%s",s1[i],s2[i]);
        }
        for(int i = 0;i < p;i ++)
            for(int j = 0;j < p;j ++)
        {
            if(strcmp(s1[i],s2[j]) == 0 || strcmp(s1[j],s2[i]) == 0)
                g[i + 1][j + 1] = 1;
        }
        un = vn = p;
        int ans = hungary();
        cout << p - ans / 2 << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值