题目: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;
}