POJ3692——Kindergarten (二分图求最小顶点覆盖 (即最大匹配))

Description

In a kindergarten, there are a lot of kids. All girls of the kids know each other and all boys also know each other. In addition to that, some girls and boys know each other. Now the teachers want to pick some kids to play a game, which need that all players know each other. You are to help to find maximum number of kids the teacher can pick.

Input

The input consists of multiple test cases. Each test case starts with a line containing three integers
G, B (1 ≤ G, B ≤ 200) and M (0 ≤ M ≤ G × B), which is the number of girls, the number of boys and
the number of pairs of girl and boy who know each other, respectively.
Each of the following M lines contains two integers X and Y (1 ≤ X≤ G,1 ≤ Y ≤ B), which indicates that girl X and boy Y know each other.
The girls are numbered from 1 to G and the boys are numbered from 1 to B.

The last test case is followed by a line containing three zeros.

Output

For each test case, print a line containing the test case number( beginning with 1) followed by a integer which is the maximum number of kids the teacher can pick.

Sample Input

2 3 3
1 1
1 2
2 3
2 3 5
1 1
1 2
2 1
2 2
2 3
0 0 0
Sample Output

Case 1: 3
Case 2: 4

大致题意:有g个女孩,b个男孩,女孩子之间互相都认识,男孩子之间也都互相认识,有部分男孩认识部分女孩,现在让你选出一些孩子前提是他们互相都认识,问最多能选多少个孩子。

思路:根据男孩女孩是否认识建立一张图mp[i][j] ,用0,1表示第i个女孩和第j个男孩之间是否认识,0表示认识,1表示不认识。然后我们找出最少的点来覆盖所有不认识的线,这样我们只需删掉其中一半的点即可使得剩下的人都互相认识。求最小顶点覆盖即是求最大匹配。套dfs匈牙利算法求最大匹配。

代码如下

#include  
#include 
#include 
#include 
#include 
#include 
using namespace std; 
#define ll long long int 
int g,b,m;
int mp[210][210];//左到右,女孩到男孩匹配
int vis[210];
int linker[210]; 
bool dfs(int gg)//从左边开始找 
{
    for(int bb=1;bb<=b;bb++)
    if(mp[gg][bb]&&!vis[bb])
    {
        vis[bb]=1;
        if(linker[bb]==-1||dfs(linker[bb]))
        {
            linker[bb]=gg;
            return true;
        }
    }
    return false;
}

int hungary()
{
    int sum=0;

    memset(linker,-1,sizeof(linker));
    for(int i=1;i<=g;i++)
    {
        memset(vis,0,sizeof(vis));
        if(dfs(i)) sum++;
    }
    return sum;
}
int main() 
{  
    int cas=0;
    while(scanf("%d%d%d",&g,&b,&m)&&(g+b+m))
    {
        cas++;
        for(int i=1;i<=g;i++)//初始化男女之间都不认识
        for(int j=1;j<=b;j++)
        mp[i][j]=1;

        while(m--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            mp[x][y]=0;
        }
        int nod=hungary();//找出需要删的点的个数
         printf("Case %d: %d\n",cas,g+b-nod);
    }
    return 0;
}

你可能感兴趣的:(二分匹配)