UVA 11080 - Place the Guards(二分图判定)

UVA 11080 - Place the Guards

题目链接

题意:一些城市,之间有道路相连,现在要安放警卫,警卫能看守到当前点周围的边,一条边只能有一个警卫看守,问是否有方案,如果有最少放几个警卫

思路:二分图判定,判定过程记录下白点和黑点个数,小的就是要安放的个数,注意如果是0,那么应该是加1

代码:

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;

const int N = 205;

int color[N];
vector<int> g[N];

int b, w;

int bipartite(int u) {
	if (color[u] == 1) b++;
	if (color[u] == 2) w++;
	for (int i = 0; i < g[u].size(); i++) {
		int v = g[u][i];
		if (color[u] == color[v]) return false;
		if (!color[v]) {
			color[v] = 3 - color[u];
			if (!bipartite(v)) return false;
		}
	}
	return true;
}

int t, n, m;

int solve() {
	int ans = 0;
	for (int i = 0; i < n; i++) {
		if (!color[i]) {
			color[i] = 1;
			b = w = 0;
			if (!bipartite(i)) return -1;
			ans += max(1, min(b, w));
		}
	}
	return ans;
}

int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &m);
		for (int i = 0; i < n; i++) {
			g[i].clear();
			color[i] = 0;
		}
		int u, v;
		while (m--) {
			scanf("%d%d", &u, &v);
			g[u].push_back(v);
			g[v].push_back(u);
		}
		printf("%d\n", solve());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值