当前位置: 代码迷 >> 综合 >> HDU 1068 Girls and Boys(二分图匹配+最大独立集+匈牙利算法)
  详细解决方案

HDU 1068 Girls and Boys(二分图匹配+最大独立集+匈牙利算法)

热度:69   发布时间:2023-11-17 14:26:17.0

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

题解:

题意:

给一堆相互认识的人的标号,人数的人数和哪些人,求最多有几人都相互不认识,就是最大独立集问题

思路:

最大独立集=顶点数-最大匹配数,直接匈牙利算法搞出互相人数的人的最大两两匹配数,然后用总人数减一下就好了

ps:

这题邻接表的写法比邻接矩阵会快上5-10倍

代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
#include<math.h>
#include<string>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include <algorithm>
using namespace std;
#define INF 1008611111
#define lson k*2
#define rson k*2+1
#define M (l+r)/2
int used[1005];
int vis[1005];
int p[1005][105];
int num[1005];
int find(int u)//匈牙利算法邻接表模板
{int i,v;for(i=0;i<num[u];i++){v=p[u][i];if(!vis[v]){vis[v]=1;if(used[v]==-1||find(used[v])){used[v]=u;return 1;}}}return 0;
}
int main()
{int i,j,k,n,m,x;while(scanf("%d",&n)!=EOF){for(i=0;i<n;i++){scanf("%d: (%d)",&x,&num[i]);//输入有些特殊for(j=0;j<num[x];j++){scanf("%d",&p[x][j]);}}int ans=0;memset(used,-1,sizeof(used));//因为这里有0所以初始化-1for(i=0;i<n;i++){memset(vis,0,sizeof(vis));if(find(i))ans++;}ans/=2;//因为二分图是对称的一对匹配算了两次printf("%d\n",n-ans);//最大独立集=顶点数-最大匹配}return 0;
}