杭电OJ——1068 Girls and Boys(二分图)

来源:互联网 发布:吕丽萍反对同性恋知乎 编辑:程序博客网 时间:2024/06/03 15:29

Girls and Boys


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
70: (3) 4 5 61: (2) 4 62: (0)3: (0)4: (2) 0 15: (1) 06: (2) 0 130: (2) 1 21: (1) 02: (1) 0
 

Sample Output
52
 

Source
Southeastern Europe 2000
 

Recommend
JGShining
 

方法:最大独立集、最大匹配

思想:

最大独立集指的是两两之间没有边的顶点的集合,顶点最多的独立集成
为最大独立集。二分图的最大独立集=节点数-(减号)最大匹配数。

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"。

由于本题是要找出最大的没有关系的集合,即最大独立集。而求最大独立集重点在于求最大匹配数,
本题中给出的是同学之间的亲密关系,并没有指出哪些是男哪些是女,所以求出的最大匹配数
要除以2才是真正的匹配数。
关于匈牙利算法:http://blog.csdn.net/lishuhuakai/article/details/8123878
发代码:
//关于题目意思的理解:二分图的匹配问题,题目给出了同学之间的亲密关系,没有指出是男是女//匈牙利算法!又遇到过这种算法//先敲一段匈牙利算法!#include<iostream>using namespace std;const int Max=500;int num;int g[Max][Max];int linker[Max];bool used[Max];bool dfs(int u){int v;for(v=0;v<num;v++){if(g[u][v] && !used[v]){used[v]=true;if(linker[v]==-1 || dfs(linker[v])){linker[v]=u;return true;}}}return false;}int hungary(){int res=0;int u;memset(linker,-1,sizeof(linker));for(u=0;u<num;u++){memset(used,0,sizeof(used));if(dfs(u)) res++;}return res;}int main(){int a,b,c;int cases;while(scanf("%d",&cases)!=EOF){num=cases;int m;memset(g,0,sizeof(g)); while(cases--)          {               scanf("%d: (%d)",&a,&b);                    for(int i=0;i<b;i++)                        {                    scanf("%d",&c);                 g[a][c]=1;             }          }         printf("%d\n",num-hungary()/2);  }return 0;}