二分匹配--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;
} 

 

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