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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
char a[1005][12];
char b[1005][12];
int g[1005][521];
bool vis[1005];
int linker[1005];
int n, p;
bool DFS(int u)
{
for(int v=0;v<p;v++)
{
if(g[u][v]&&!vis[v])
{
vis[v] = true;
if(linker[v]==-1||DFS(linker[v]))
{
linker[v] = u;
return true;
}
}
}
return false;
}
int hungry()
{
int res = 0;
memset(linker, -1, sizeof(linker));
for(int u=0;u<p;u++)
{
memset(vis, false, sizeof(vis));
if(DFS(u))
res++;
}
return res;
}
int main()
{
int m;
while(~scanf("%d %d %d", &n, &m, &p))
{
for(int i=0;i<p;i++)
{
scanf("%s %s", a[i], b[i]);
}
memset(g, 0, sizeof(g));
for(int i=0;i<p;i++)
{
for(int j=i+1;j<p;j++)
{
if(strcmp(a[i], b[j])==0||strcmp(a[j], b[i])==0)//判断是否矛盾,建图
{
g[i][j] = 1;
g[j][i] = 1;
}
}
}
printf("%d\n", p - hungry()/2);//最大独立集=顶点数-最大匹配
}
return 0;
}
本文介绍了一个有趣的编程问题:动物园管理员如何通过移除某些动物来最大化孩子们的快乐度。每个孩子都有最喜欢的动物和最不喜欢的动物,管理员的目标是让尽可能多的孩子开心。文章提供了一个高效的解决方案,并附带了完整的代码实现。
19万+

被折叠的 条评论
为什么被折叠?



