hdu 1068 Girls and Boys (二分匹配)

时间:2021-07-18 22:30:33

Girls and Boys

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6867    Accepted Submission(s): 3083

Problem Description
the second year of the university somebody started a study on the romantic relations between the students. The relation “romantically involved” is defined between one girl and one boy. For the study reasons it is necessary to find out the maximum set satisfying the condition: there are no two students in the set who have been “romantically involved”. The result of the program is the number of students in such a set.

The input contains several data sets in text format. Each data set represents one set of subjects of the study, with the following description:

the number of students
the description of each student, in the following format
student_identifier:(number_of_romantic_relations) student_identifier1 student_identifier2 student_identifier3 ...
or
student_identifier:(0)

The student_identifier is an integer number between 0 and n-1, for n subjects.
For each given data set, the program should write to standard output a line containing the result.

Sample Input
7
0: (3) 4 5 6
1: (2) 4 6
2: (0)
3: (0)
4: (2) 0 1
5: (1) 0
6: (2) 0 1
3
0: (2) 1 2
1: (1) 0
2: (1) 0
Sample Output
5
2
Source
Recommend
JGShining   |   We have carefully selected several similar problems for you:  1507 1528 1054 1498 1083 

二分匹配入门题:

给出邻接矩阵和邻接表的做法:

一般数据大时邻接表会快很多。

邻接矩阵:

 //2437MS    4188K    907 B    C++
#include<stdio.h>
#include<string.h>
#define N 1005
int g[N][N];
int match[N];
int vis[N];
int n;
int dfs(int x)
{
for(int i=;i<n;i++)
if(!vis[i] && g[x][i]){
vis[i]=;
if(match[i]==- || dfs(match[i])){
match[i]=x;
return ;
}
}
return ;
}
int hungary()
{
int ret=;
memset(match,-,sizeof(match));
for(int i=;i<n;i++){
memset(vis,,sizeof(vis));
ret+=dfs(i);
}
return ret;
}
int main(void)
{
int a,m,b;
while(scanf("%d",&n)!=EOF)
{
memset(g,,sizeof(g));
for(int i=;i<n;i++){
scanf("%d: (%d)",&a,&m);
for(int j=;j<m;j++){
scanf("%d",&b);
g[a][b]=g[b][a]=;
}
}
printf("%d\n",n-hungary()/);
}
return ;
}

邻接表:

 //203MS    268K    1169 B    C++
#include<stdio.h>
#include<string.h>
#define N 1005
struct node{
int v;
int next;
}edge[*N];
int match[N];
int vis[N];
int head[N];
int n,edgenum;
void addedge(int u,int v)
{
edge[edgenum].v=v;
edge[edgenum].next=head[u];
head[u]=edgenum++;
}
int dfs(int x)
{
for(int i=head[x];i!=-;i=edge[i].next){
int v=edge[i].v;
if(!vis[v]){
vis[v]=;
if(match[v]==- || dfs(match[v])){
match[v]=x;
return ;
}
}
}
return ;
}
int hungary()
{
int ret=;
memset(match,-,sizeof(match));
for(int i=;i<n;i++){
memset(vis,,sizeof(vis));
ret+=dfs(i);
}
return ret;
}
int main(void)
{
int a,b,m;
while(scanf("%d",&n)!=EOF)
{
edgenum=;
memset(head,-,sizeof(head));
for(int i=;i<n;i++){
scanf("%d: (%d)",&a,&m);
while(m--){
scanf("%d",&b);
addedge(a,b);
addedge(b,a);
}
}
printf("%d\n",n-hungary()/);
}
return ;
}