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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章