最大独立集

// 最大独立集.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

/*
http://oj.daimayuan.top/course/14/problem/799

给你一张二分图,图中没有重边,你需要求出这张图中最大独立集包含的顶点个数。

最大独立集是指:在图中选出最多的点,满足他们两两之间没有边相连。

图用以下形式给出:

第一行输入两个整数 n,m
,表示图的顶点数和边数,顶点编号从 1到 n。

接下来 m 行,每行两个整数 x,y
,表示 x 和 y 之间有一条边。

输出一个数为最大独立集大小。

输入格式
第一行两个整数 n,m。

接下来 m 行,每行有两个整数,代表一条边。

输出格式
输出一个数表示答案。

样例输入
4 3
1 2
1 4
3 4
样例输出
2
数据规模
对于所有数据,保证 2≤n≤1000,0≤m≤10000,1≤x,y≤n,x≠y。
*/


#include <iostream>
#include <cstring>

using namespace std;

const int N = 1010;
const int M = 20010;
int h[N], e[M], ne[M], idx;
bool st[N];
int match[N];
int n, m;
int color[N];

void add(int a, int b) {
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

bool find(int x) {
	for (int i = h[x]; i != -1; i = ne[i]) {
		int j = e[i];
		if (!st[j]) {
			st[j] = true;
			if (match[j] ==0 || find(match[j])) {
				match[j] = x;
				return true;
			}

		}
	}

	return false;
}

void dfs(int x,int c) {
	if (color[x] == c) return;
	color[x] = c;

	for (int i = h[x]; i != -1; i = ne[i]) {
		int j = e[i];
		if (color[j] == 0) {
			dfs(j, 3 - c);
		}
	}
}


int main()
{
	cin >> n >> m;
	memset(h, -1, sizeof h);
	for (int i = 0; i < m; i++) {
		int a, b; cin >> a >> b;
		add(a, b); add(b, a);
	}

	for (int i = 1; i <= n; i++) {
		if (color[i] == 0) {
			dfs(i, 1);
		}
	}
	

	int res = 0;
	for (int i = 1; i <= n; i++) {
		if (color[i] == 2) continue;
		memset(st, 0, sizeof st);
		if (find(i)) res++;
	}

	cout << (n-res) << endl;


	return 0;
}

 

posted on 2024-08-13 16:46  itdef  阅读(2)  评论(0编辑  收藏  举报

导航