B - Girls and Boys
the second year of the university somebody started astudy on the romantic relations between the students. The relation“romantically involved” is defined between one girl and one boy. For the studyreasons 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”. Theresult of the program is the number of students in such a set.
The input contains several data sets in text format. Each data set representsone 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_identifier1student_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 linecontaining the result.
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
Output
5
2
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
题意:输入一个数字n,接下来n行数据,每一行第一个数字表示一个点,然后括号内的数字m表示与这个点相连的点的个数,然后是m个相连的点,输出最大独立集合。
思路:二分图最大独立集合 = 节点数 - 最大匹配数。
#include<stdio.h>
#include<string.h>
int a[1000][1000],book[1000],match[1000];
int m;
int dfs(int u)//匈牙利算法
{
int i;
for(i=0;i<m;i++)
{
if(book[i]==0&&a[u][i]==1)
{
book[i]=1;
if(match[i]==0||dfs(match[i]))
{
match[i]=u;
return 1;
}
}
}
return 0;
}
int main()
{
int i,j,k,t1,t2,t3,sum,n;
while(scanf("%d",&m)!=EOF)
{
n=m;
memset(a,0,sizeof(a));
memset(match,0,sizeof(match));
for(i=0;i<m;i++)
{
scanf("%d: (%d)",&t1,&t2);//不用换成字符串判断输入
for(j=0;j<t2;j++)
{
scanf("%d",&t3);
a[t1][t3]=1;
}
}
/* for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
printf("%d ",a[i][j]);
printf("\n");
}
*/
sum=0;
for(i=0;i<m;i++)
{
memset(book,0,sizeof(book));
if(dfs(i))
sum++;//计算最大匹配数
}
printf("%d\n",n-sum/2);//输入最大独立集合
}
return 0;
}

本文介绍了一种解决二分图中寻找最大独立集问题的方法。通过使用匈牙利算法来计算二分图的最大匹配数,并据此求得最大独立集的大小。提供了完整的C语言实现代码,包括输入学生间浪漫关系的数据结构定义及最大匹配数的计算。
180

被折叠的 条评论
为什么被折叠?



