HDU 1068 Girls and Boys(匈牙利算法求最大獨立集)

Problem 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.c++

The input contains several data sets in text format. Each data set represents one set of subjects of the study, with the following description:ide

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)spa

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

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) 0orm

Sample Output

5
2ip

題意

題目給定一些男女生之間相互的 romantic 關係,要求找出一個最大的集合,使得該集合中的全部男女生之間都不存在 romantic 關係。input

分析

一個二分圖的最大獨立集點數與最大二分匹配個數有直接的關係:it

\[最大獨立集點數 = 頂點數 - 最大二分匹配對數 \]

故本題直接轉化爲求最大二分匹配便可,須要注意的是,題中給出的條件是 1 指向 2,2 也會指向 1,因此最終算出來的匹配數實際上是實際對數的兩倍,最終被頂點數減去以前首先須要折半。io

基礎二分匹配練手題。form

#include<bits/stdc++.h>
#define sd(n) scanf("%d",&n)
using namespace std;
const int N = 1e3 + 10;
int e[N][N], match[N];
bool book[N];
int n, f[N];

bool dfs(int x) {
	for (int i = 0; i < n; ++i) {
		if (e[x][i] && !book[i]) {
			book[i] = true;
			if (match[i] == -1 || dfs(match[i])) {
				match[i] = x;
				return true;
			}
		}
	}
	return false;
}

int main() {
	while (~scanf("%d", &n)) {
		memset(e, 0, sizeof e);//多組輸入,別忘記初始化圖啊,TLE幾發了。。。
		for (int i = 0; i < n; i++)
			match[i] = -1;
		for (int i = 0; i < n; ++i) {
			int t1, t2, u;
			scanf("%d: (%d)", &t1, &t2);
			for (int j = 0; j < t2; j++){
				scanf("%d", &u);
				e[t1][u] = 1;
			}
		}
		int cnt = 0;
		for (int i = 0; i < n; ++i) {
			memset(book, false, sizeof book);
			if (dfs(i))
				cnt++;
		}
		cout << n - cnt / 2 << endl;
	}
}
相關文章
相關標籤/搜索