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

weixin_30639719發表於2020-04-05

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;
}


轉載於:https://www.cnblogs.com/yxwkf/p/5095142.html

相關文章