Girls and Boys POJ - 1466 【(二分图最大独立集)】

Problem 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.

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
题意:有n个学生,每个学生都和一些人又关系,找出互相没关系的最多的一群人。

思路:这是一道二分图最大独立集模板题【最大独立集= 点数 - 最大匹配数】注意:最大匹配数需要除以2

【参考博客】

看到之后就可以发现,这是一道非常明显的最大独立集的问题,可以转化为二分图来做,还是最经典的拆点建图,然后根据定理,最大独立集=顶点数-最小点覆盖数。  而对于这道题来说,我们可以发现这个浪漫关系是相互的。

而我们的建图中,按理来说应该是一边是男的点,一边是女的点这样连边,但是题目中没说性别的问题。

只能将每个点拆成两个点,一个当作是男的点,一个当作是女的点了,然后连边。由于关系是相互的,这样就造成了边的重复。也就是边集是刚才的二倍,从而导致了最大匹配变成了二倍。

那么 ,最大独立集=顶点数-最大匹配/2,所以最终答案就呼之欲出了。

AC代码:

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<stdio.h>
 4 #include<string.h>
 5 #include<vector>
 6 using namespace std;
 7 
 8 #define maxn 666
 9 vector<int> v[maxn];
10 int vis[maxn];
11 int match[maxn];
12 int n;
13 int dfs(int u){
14     for(int i=0;i<v[u].size();i++){
15         int temp=v[u][i];
16         if(vis[temp]==0){
17             vis[temp]=1;
18             if(match[temp]==0||dfs(match[temp])){
19                 match[temp]=u;
20                 return 1;
21             }
22         }
23     }
24     return 0;
25 }
26 int main(){
27     while(~scanf("%d",&n)){
28         for(int i=0;i<n;i++)
29             v[i].clear();
30         int x,m,y;
31         for(int i=1;i<=n;i++){
32             scanf("%d: (%d)",&x,&m);
33             for(int j=0;j<m;j++){
34                 scanf("%d",&y);
35                 v[x].push_back(y);
36                 //v[y].push_back(x);
37             }
38         }
39         memset(match,0,sizeof(match));
40         int ans=0;
41         for(int i=0;i<n;i++){
42             for(int j=0;j<=n;j++)
43                 vis[j]=0;
44             if(dfs(i))
45                 ans++;
46         }
47         printf("%d\n",n-ans/2); 
48     }
49     return 0;
50 } 

猜你喜欢

转载自www.cnblogs.com/pengge666/p/11625982.html