hdu2458 Kindergarten [二分匹配模板]

Kindergarten

hdu2458 題目鏈接

Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1382 Accepted Submission(s): 733

Problem 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

Source

2008 Asia Hefei Regional Contest Online by USTC

解題思路

這題是說老師要帶小朋友做遊戲,男孩之間相互全部認識,女孩之間全部相互認識。現在要選一些人來做遊戲,要求選取的人必須全部互相認識的,問最多選取多少人。

這裏必須要求所有人全部都相互認識,正向考慮的話就比較麻煩了。然後我的想法就是不認識的人的關係定爲0.求一個最大的匹配數,就表示這些匹配的人之間相互不認識,求出不認識的人的最大匹配數,然後拿總人數減去這些人之後其他的就是全部互相兩兩認識了。

二分匹配模板

程序代碼

#include <stdio.h>
#include <string.h>
int n,g,b;
int match[420];
int book[420];
int map[420][420];

int dfs(int x){
    int i;
    for(i=1;i<=b;i++){
        if(!map[x][i]&&book[i]==0){
            book[i]=1;
            if(match[i]==0||dfs(match[i])){ //如果這個人沒有匹配或者能更換對象 
                match[i]=x;
                return 1;
            }   
        }
    }
    return 0;
}

int main()
{
    int i,j,k;
    int u,v,t=1;
    while(scanf("%d%d%d",&g,&b,&k)!=EOF){
        if(g+b+k==0)
            break;
        n=g+b;
        memset(map,0,sizeof(map));
        memset(match,0,sizeof(match));
        for(i=0;i<k;i++){
            scanf("%d%d",&u,&v);
            map[u][v]=1;        //這裏是單向的,因爲男孩1和女孩1不同 
        //  map[v][u]=1;
        }
        k=0;
        for(i=1;i<=g;i++){
            memset(book,0,sizeof(book));
            if(dfs(i)==1)
                k++;
        }
        printf("Case %d: %d\n",t++,n-k);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章