HDU 1068 Girls and Boys ———— 匈牙利算法

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

Input

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 (n <=500 ), for n subjects.

Output

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

 

思路:

先用匈牙利算法求出最大戀愛關係的匹配數,然後因爲關係是相互的,所以要除以2,然後用總人數減掉這個數,就是保證不會戀愛人數的最大。

ac代碼:

#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>

#define MAXN 505
#define INF 0x3f3f3f3f

using namespace std;

int n;
bool edge[MAXN][MAXN], vis[MAXN];
int match[MAXN];

int dfs(int u) {
	for (int i = 0; i <= n-1; i++) {
		if (vis[i] == false && edge[u][i] == true) {
			vis[i] = true;
			if (match[i] == 0 || dfs(match[i])) {
				match[i] = u;
				return 1;
			}
		}
	}
	return 0;
}

int main() {
	
	while (scanf("%d", &n) != EOF && n != 0) {
		memset(match, 0, sizeof(match));
		memset(edge, false, sizeof(edge));
		for (int i = 0; i <= n - 1; i++) {
			int nouse, t;
			scanf("%d: (%d)", &nouse, &t);
			for (int j = 0; j <= t - 1; j++) {
				int v;
				scanf("%d", &v);
				edge[i][v] = true;
			}
		}
		int sum = 0;
		for (int i = 0; i <= n - 1; i++) {
			memset(vis, false, sizeof(vis));
			if (dfs(i)) {
				sum++;
			}
		}
		printf("%d\n", n - sum/2);
	}


	return 0;
}

 

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