HDU-3829-Cat VS Dog(二分匹配)

                                                         Cat VS Dog
 


Problem Description

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个人,每个人有喜欢的动物和讨厌的动物,如果保留他喜欢的删去讨厌的他就很高兴,问最多让多少人高兴,每行的两个字符串分别表示该人喜欢和不喜欢的动物或者是不喜欢和喜欢的动物,在建图的时候如果一个人喜欢的动物是另一个人不喜欢的动物,那么把该点双向记为1,然后求最大独立集

程序代码:

#include<stdio.h>
#include<string.h>
int e[1010][1010],match[1010],book[1010],n,m,k;
char s1[1010][10],s2[1010][10];
int dfs(int u);
int main()
{
	int i,j,a,b,sum;
	while(scanf("%d%d%d",&n,&m,&k)!=EOF)
	{
		sum=0;
		memset(e,0,sizeof(e));
		memset(match,0,sizeof(match));
		for(i=1;i<=k;i++)
			scanf("%s%s",s1[i],s2[i]);	
		for(i=1;i<=k;i++)
			for(j=1;j<=k;j++)
				if(strcmp(s1[i],s2[j])==0)
					e[i][j]=e[j][i]=1;	
		for(i=1;i<=k;i++)
		{
			memset(book,0,sizeof(book));
			if(dfs(i)==1)
				sum++;
		}
		printf("%d\n",k-sum/2);
	}
	return 0;
}
int dfs(int u)
{
	int i;
	for(i=1;i<=k;i++)
		if(book[i]==0&&e[u][i]==1)
		{	
			book[i]=1;
			if(match[i]==0||dfs(match[i])==1)
			{
				match[i]=u;
				return 1;
			}
		}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/81563789