二分匹配--Girls and Boys

Girls and Boys

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

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

思想:(转)

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

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才是真正的匹配数。

 

#include<stdio.h>
#include<string.h>
#define MAX 500

int num;
int line[MAX][MAX];
int used[MAX];
int human[MAX]; 

bool find(int x){ 
	int i,j;
	for(j = 0;j<num;j++){//扫描每个人 
		if(line[x][j]==true&&used[j]==false){//两人相互喜欢且无标记 
			used[j] = 1;
			if(human[j]==0||find(human[j])){//查看是否配对过或标记 
				human[j] = x;
				return true;
			}
		}
	}
	return false;
}


int main(){
	while(scanf("%d",&num)!=EOF){
		//初始化
		memset(line,0,sizeof(line));
		memset(human,0,sizeof(human));
		//输入 
		int a,b,c;
		for(int i = 0;i<num;i++){
			scanf("%d: (%d)",&a,&b);
			for(int j = 0;j<b;j++){
				scanf("%d",&c);
				line[a][c] = 1;
			}
		}
		//核心算法 
		int all = 0;
		for(int i = 0;i<num;i++){
			memset(used,0,sizeof(used));
			if(find(i)) all++;
		} 
		//输出 
		printf("%d\n",num-all/2);
	}
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章