L - Cat VS Dog(匈牙利)

本文介绍了一个有趣的编程问题:动物园管理员如何通过移除某些动物来最大化孩子们的快乐度。每个孩子都有最喜欢的动物和最不喜欢的动物,管理员的目标是让尽可能多的孩子开心。文章提供了一个高效的解决方案,并附带了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值