AcWing 257. 关押罪犯 二分图 染色法

Acwing257关押罪犯

题目链接

Meaning

给定两座监狱,其中有 N N N 名罪犯,编号为 1 ∼ n 1\sim n 1n ,两名罪犯之间的怨气值为 c c c 。题目通过给出关系对 a , b , c a,b,c a,b,c 来表示罪犯 a , b a,b a,b 之间会产生怨气值为 c c c 的矛盾,我们要将罪犯分到两个监狱,使得同一个监狱中的恩怨值的最大值最小

Solution

  • a , b , c a,b,c a,b,c 看成点,点,边权。罪犯之间的恩怨相当于在他们之间连一条边
  • 考虑一条数轴,假定一个答案 x x x,在恩怨值大于答案的关系分到两个监狱,否则可以在一个监狱
  • 这样,大于这个答案 x x x 的所有边都是二分图,小于 x x x 的任何数都不满足这样的性质
  • 通过二分 x x x 加上判断以 x x x 为界的图是不是二分图得到答案

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
#define debug(a) cout << #a << " " << a << endl
const int maxn = 1500;
const int N = 2e5 + 7, M = N * 2;
const int inf = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
inline long long read();

int h[N], e[M], ne[M], w[M], idx;
int n, m;
int color[M];

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

bool dfs(int u, int c, int mid) {
	color[u] = c;
	for(int i = h[u]; ~i; i = ne[i]) {
		if(w[i] <= mid) continue;
		int j = e[i];
		if(color[j]) {
			if(color[j] == c) return false;
		}
		else if (!dfs(j, 3 - c, mid)) return false;
	}
	return true;
}

bool check(int mid) {
	memset(color, 0, sizeof color);

	for(int i = 1; i <= n; i++) {
		if(color[i] == 0) {
			if(!dfs(i, 1, mid)) return false; //初始染色
		}
	}
	return true;
}



int main() {

//	freopen("input.txt", "r", stdin);
//	freopen("output.txt", "w", stdout);

	ios::sync_with_stdio(false);
	cin >> n >> m;
	memset(h, -1, sizeof(h));
	while(m--) {
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c), add(b, a, c);
	}

	int l = 0, r = 1e9;
	while(l < r) {
		int mid = l + r >> 1;
		if(check(mid)) r = mid;
		else l = mid + 1;
	}

	cout << l << '\n';




	return 0;
}


/*
数组开够了吗 开到上界的n+1次方
初始化了吗
*/







inline LL read() {
	char ch = getchar();
	LL p = 1, data = 0;
	while(ch < '0' || ch > '9') {
		if(ch == '-')p = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9') {
		data = data * 10 + (ch ^ 48);
		ch = getchar();
	}
	return p * data;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值