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
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.
二分匹配入门题:
给出邻接矩阵和邻接表的做法:
一般数据大时邻接表会快很多。
邻接矩阵:
//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 ;
}