HDUOJ 3829 Cat VS Dog

HDUOJ 3829 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

这题是一道二分图最小边覆盖,比较难的地方就是构图~
我们可以将人与人建边,就是喜欢的动物和别人讨厌的动物一样或者讨厌的动物和别人喜欢的动物一样,则在这两人之间建边,然后再求最下边覆盖即可,AC代码如下:

#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
const int N=505;
int match[N],vis[N],g[N][N];
int n,m,p;
struct node{
    string like,dislike;
}P[N];

int found(int u){
    for(int v=1;v<=p;v++){
        if(!vis[v] && g[u][v]){
            vis[v]=1;
            if(!match[v] || (found(match[v]))){
                match[v]=u;
                return 1;
            }
        }
    }
    return 0;
}

void hungary(){
    int ans=0;
    fill(match,match+N,0);
    for(int i=1;i<=p;i++){
        fill(vis,vis+N,0);
        if(found(i)) ans++;
    }
    printf("%d\n",p-ans/2);
}

int main(){
    while(~scanf("%d%d%d",&n,&m,&p)){
        fill(g[0],g[0]+N*N,0);
        fill(vis,vis+N,0);
        for(int i=1;i<=p;i++){
            cin>>P[i].like>>P[i].dislike;
        }
        for(int i=1;i<=p;i++){
            for(int j=i+1;j<=p;j++){
                if(P[i].like==P[j].dislike || P[i].dislike==P[j].like){
                    g[i][j]=1;
                    g[j][i]=1;
                }
            }
        }
        hungary();
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章