Girls and Boys
Time Limit: 5000MS | Memory Limit: 10000K | |
Total Submissions: 12717 | Accepted: 5659 |
Description
In 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.
Input
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 (n <=500 ), for n subjects.
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 (n <=500 ), for n subjects.
Output
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
【解析】
题意 在一群有恋爱关系的男女中选出两两之间没有恋爱关系的人,使人数最多。
方法:二分图求最大独立集,最大独立集=点数-最大匹配。
没有恋爱关系说明没有连边,就是求最大独立集。最大独立集中的点两两之间没有连边。
由于性别未知,所以求的最大匹配/2。因为原来二分图是男的一边女的一边,而现在二分图左边是所有人右边也是所有人,所以要/2'
注意:学生的标号从0开始,所以for(int i=0;i<n;i++).
【code】
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define N 500+10 int map[N][N],match[N]; int cnt,n,m,id,num,po; bool vis[N]; bool path(int x) { for(int i=0;i<n;i++) { if(!vis[i]&&map[x][i]) { vis[i]=1; if(!match[i]||path(match[i])) { match[i]=x; return true; } } } return false; } int main() { while(cin>>n) { cnt=0; memset(map,0,sizeof(map)); memset(match,0,sizeof(match)); for(int i=1;i<=n;i++) { scanf("%d: (%d)",&id,&num); for(int j=1;j<=num;j++) { scanf("%d",&po); map[id][po]=1; } } for(int i=0;i<n;i++) { memset(vis,0,sizeof(vis)); if(path(i))cnt++; } cout<<n-cnt/2<<endl; } return 0; }