Cat VS Dog——最大独立集

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=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

题目翻译

‎动物园里有N只猫和M狗,今天有P孩子去动物园,每个孩子都有喜欢的动物和不喜欢的动物,如果孩子喜欢的动物是猫,那么他/她不喜欢的动物一定是狗,反之亦然。‎
‎现在动物园管理员正在移除一些动物,如果一个孩子的类动物没有被移除,他/她的不喜欢的动物被移除,他/她会很高兴。因此,管理员想知道他应该删除哪些动物,以使尽可能多的快乐孩子。‎

‎输入‎

‎输入文件包含多个测试用例,对于每个案例,第一行包含三个整数 N <= 100、M <= 100 和 P <= 500。‎
‎下一个P线,每行包含一个孩子的喜欢动物和不喜欢的动物,C为猫和D为狗。(详情请参阅示例)‎

‎输出‎

‎对于每种情况,输出单个整数:快乐儿童的最大数量‎

 

这个题的关键在于怎么转换建图,根据题意我们知道,我们不能直接把猫和狗当成节点。我们不妨这样想,把每个孩子当做一个节点,如果一个孩子的喜欢的动物恰好和另一个孩子不喜欢的动物相同(或者相反) ,那么这两个孩子连上一条边。最后的结果就是求该二分图的最大独立集(就是相互不影响的最多的点),最大独立集=结点总数-最大匹配数,这里因为是无向图,所以要除2.

 

#include <iostream>
#include<cstring> 
using namespace std;
int n,m,p;
int nxt[505],visited[505],G[505][505];
int cnt;
pair<string,string> s[505];
int find(int x){
	for(int i = 1;i<=p;++i){
		if(!visited[i]&&G[x][i]){
			visited[i]=1;
		    if(nxt[i]==-1||find(nxt[i])){
		    	nxt[i]=x;
		    	return 1;
			}
		}
	}
	return 0;
}
int match()
{
	int ans=0;
	memset(nxt,-1,sizeof(nxt));
	for(int i = 1;i<=p;++i){
		memset(visited,0,sizeof(visited));
		if(find(i))  ans++;
	}
	return ans;
}
int main(int argc, char** argv) {
	while(cin>>n>>m>>p){
		cnt=0;
		memset(G,0,sizeof(G));
		getchar();
		for(int i = 1;i<=p;++i){
			cin>>s[i].first>>s[i].second;
			for(int j = 1;j<=i;++j){
				if(s[i].first==s[j].second||s[i].second==s[j].first)
					G[i][j]=G[j][i]=1;
			}
		}
		cout<<p-match()/2<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值