1. 程式人生 > >Cat VS Dog (二分匹配)

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<stdio.h>
#include<string.h>

int n,m,p;
int match[505],book[505],map[505][505];
int uN, vN;
int like[2][505], dislike[2][505];
int dfs(int u)
{
	int i;
	for (i = 0; i < vN; i ++)
	{
		if(book[i] == 0 && map[u][i] == 1)
		{
			book[i] = 1;
			if(match[i] == 0 || dfs(match[i]))
			{
				match[i] = u;
				return 1;
			}
		}
	}
	return 0;
}
int main()
{
	int i,j,sum,num1,num2;
	char tmp1, tmp2;
	while(scanf("%d%d%d",&n,&m,&p) != EOF)
    {
    	sum = 0;
        uN = vN = 0;
        memset(match,0,sizeof(match));
        for(i = 0; i < p; i ++)
        {
            getchar();
            scanf("%c%d",&tmp1, &num1);
            getchar();
            scanf("%c%d", &tmp2, &num2);
            if(tmp1 == 'C')
            {
                like[0][uN] = num1;
                dislike[0][uN] = num2;
                uN ++;
            }
            else
            {
                like[1][vN] = num1;
                dislike[1][vN] = num2;
                vN ++;
            }
        }
        for(i = 0; i < uN; i ++)
        {
            for(j = 0; j < vN; j ++)
            {
                if(like[0][i] == dislike[1][j] || dislike[0][i] == like[1][j])
                    map[i][j] = 1;
                else
					map[i][j] = 0;
            }
        }
        for(i = 0; i < uN; i ++)
        {
        	memset(book,0,sizeof(book));
        	if(dfs(i))
        		sum ++;
		}
        printf("%d\n",p-sum);
	}
    return 0;
}