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.

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.

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

题意

题目给定一些男女生之间相互的 romantic 关系,要求找出一个最大的集合,使得该集合中的所有男女生之间都不存在 romantic 关系。

分析

一个二分图的最大独立集点数与最大二分匹配个数有直接的关系:

=

故本题直接转化为求最大二分匹配即可,需要注意的是,题中给出的条件是 1 指向 2,2 也会指向 1,所以最终算出来的匹配数其实是实际对数的两倍,最终被顶点数减去之前首先需要折半。

基础二分匹配练手题。

#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;
	}
}
posted @   RioTian  阅读(182)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
点击右上角即可分享
微信分享提示

📖目录