Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 6313 | Accepted: 3104 |
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
题目大意:
有B个男孩G个女孩。男孩之间相互认识,女孩之间相互认识。此外还有一些男孩女孩相互认识。要从这些人中选最多的人相互认识。求人数。
解题思路:
直接建图好想没有什么很好的方法能解决问题。只要我们建立一张补图,马上就可以看出这是一个最大独立集问题。
因为|最大独立集|+|最小顶点覆盖|=|V|,而且对于二分图来说:|最大匹配|=|最小顶点覆盖|。所以我们只要用二分图匹配算法求出最大匹配,再用总人数V减去它就可以得到答案。
附AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn=200+5;
const int maxv=2*maxn;
int b,g,M,land[maxv][maxv];//原图的邻接矩阵表示
int V;//顶点数
vector<int> G[maxv];//补图的邻接表表示
int match[maxv];//所匹配的顶点
bool used[maxv];//DFS中用到的访问标记
//向图中添加一条连接u和v的边
void add_edge(int u,int v)
{
G[u].push_back(v);
G[v].push_back(u);
}
//通过DFS寻找增广路
bool dfs(int v)
{
used[v]=true;
for(int i=0;i<G[v].size();++i)
{
int u=G[v][i],w=match[u];
if(w<0||!used[w]&&dfs(w))
{
match[v]=u;
match[u]=v;
return true;
}
}
return false;
}
//求解二分图最大匹配
int bipartite_matching()
{
int res=0;
memset(match,-1,sizeof match);
for(int v=0;v<V;++v)
{
if(match[v]<0)
{
memset(used,0,sizeof used);
if(dfs(v))
++res;
}
}
return res;
}
int main()
{
int tt=1;
while(~scanf("%d%d%d",&g,&b,&M)&&(g||b||M))
{
//女孩:0~g-1
//男孩;g~g+b-1
V=g+b;
memset(land,0,sizeof land);
for(int i=0;i<V;++i)
G[i].clear();
for(int i=0;i<M;++i)
{
int temp1,temp2;
scanf("%d%d",&temp1,&temp2);
--temp1;
temp2+=g-1;
land[temp1][temp2]=true;
}
for(int i=0;i<g;++i)
for(int j=g;j<g+b;++j)
if(!land[i][j])//将原图转化为补图
add_edge(i,j);
printf("Case %d: %d\n",tt++,V-bipartite_matching());
}
return 0;
}