Hdu3829 Cat VS Dog(二分图最大独立点集)

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.

题意:动物园有两种动物,猫和狗,给出每个孩子喜欢的动物和讨厌的动物,如果讨厌的动物被删除,喜欢的动物还在,则孩子会高兴,现在选择一些动物删掉,最多能有多少个孩子开心。

思路:用喜恶关系建立互斥图,求二分匹配,(也就等于求最少要去掉多少人,这个图才不会矛盾)。然后用人数减去二分匹配就是答案。(因为是一个孩子分成了两个点,所以最后要除二)。

#include<algorithm>
#include<string.h>
#include<stdio.h>
int n,m,p,g[510][510],dis[510],vis[510];
char A[510][10],B[510][10];
void init()
{
    memset(g,0,sizeof(g));
    for(int i=1;i<=p;i++)
    {
        scanf("%s%s",A[i],B[i]);
    }
    for(int i=1;i<=p;i++)
    {
        for(int j=1;j<=p;j++)
        {
            if(!strcmp(A[i],B[j]))
            {
                g[i][j]=1;
                g[j][i]=1;
            }
        }
    }
}
int found(int u)
{
    for(int i=1;i<=p;i++)
    {
        if(g[u][i]&&!vis[i])
        {
            vis[i]=1;
            if(!dis[i]||found(dis[i]))
            {
                dis[i]=u;
                return 1;
            }
        }
    }
    return 0;
}
int hun()
{
    int ans=0;
    memset(dis,0,sizeof(dis));
    for(int i=1;i<=p;i++)
    {
        memset(vis,0,sizeof(vis));
        if(found(i)) ans++;
    }
    return ans;
}
int main()
{
    while(~scanf("%d%d%d",&n,&m,&p))
    {
        init();
        printf("%d\n",p-hun()/2);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41380961/article/details/81352485