[关闭]
@Chilling 2017-02-16T17:54:02.000000Z 字数 1865 阅读 1032

HDU-1068: Girls and Boys(最大独立集)

二分图


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:

Input

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)

Output

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

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个人,然后下面有n行,每行开头先输入这个人的编号(人的编号是从0开始的),按题目的格式,括号里面是他喜欢的人的个数,后面是喜欢的人的编号。问满足最大的匹配之后,还有几只单身狗。
有意思的是,案例中出现a喜欢b,b喜欢c,同时a也喜欢c的情况,a和c应该是同性吧(///▽///)

分析:用二分图模板求得最大匹配数,用n减去最大匹配数目的一半。


  1. #include<stdio.h>
  2. #include<vector>
  3. #include<string.h>
  4. using namespace std;
  5. int n,vis[500],p[500],sum;
  6. vector<int>v[500];
  7. int match(int i)
  8. {
  9. int l=v[i].size();
  10. for(int j=0;j<l;j++)
  11. {
  12. if(vis[v[i][j]]==1)
  13. continue;
  14. vis[v[i][j]]=1;
  15. if(p[v[i][j]]==-1||match(p[v[i][j]]))
  16. {
  17. p[v[i][j]]=i;
  18. return 1;
  19. }
  20. }
  21. return 0;
  22. }
  23. int ans()
  24. {
  25. int i;
  26. sum=0;
  27. for(i=0;i<n;i++)
  28. {
  29. memset(vis,0,sizeof(vis));
  30. if(match(i)==1)
  31. sum++;
  32. }
  33. return n-sum/2;
  34. }
  35. int main()
  36. {
  37. int i,x,y,c;
  38. char ch[11];
  39. while(scanf("%d",&n)!=EOF)
  40. {
  41. memset(ch,0,sizeof(ch));
  42. memset(p,-1,sizeof(p));
  43. for(i=0;i<n;i++)
  44. {
  45. scanf("%d:",&x);
  46. scanf("%s",ch);
  47. if(sscanf(ch,"(%d)",&c)==1)
  48. {
  49. while(c--)
  50. {
  51. scanf("%d",&y);
  52. // printf("%d %d\n",x,y);
  53. v[x].push_back(y);
  54. }
  55. }
  56. }
  57. printf("%d\n",ans());
  58. for(int i=0;i<=n;i++)
  59. v[i].clear();
  60. }
  61. return 0;
  62. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注