HZOJ-327:关押罪犯

复制代码
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
#define MAX_N 20000
struct Node {
	int a, b, c;
};
set<int> s[MAX_N + 5];
int fa[MAX_N + 5], n, m;
int get(int x) {
	return fa[x] = (fa[x] == x ? x : get(fa[x]));
}
int main() {
	cin >> n >> m;
	vector<Node> arr(m);
	for (int i = 0; i <= n; i++) fa[i] = i;
	for (int i = 0, a, b, c; i < m; i++) {
		cin >> arr[i].a >> arr[i].b >> arr[i].c;
	}
	sort(arr.begin(), arr.end(), [&](Node i, Node j) -> bool {return i.c > j.c;
		});
	for (int i = 0; i < m; i++) {
		int a = arr[i].a, b = arr[i].b;
		if (get(a) == get(b)) {
			cout << arr[i].c;
			return 0;
		}
		if (!s[a].empty()) {
			fa[get(*s[a].begin())] = get(b);
		}
		if (!s[b].empty()) {
			fa[get(*s[b].begin())] = get(a);
		}
		s[a].insert(b);
		s[b].insert(a);
	}
	cout << 0;
	return 0;
}

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
#define MAX_N 20000
class UnionSet {
public:
	UnionSet(int n) : fa(n + 1), val(n + 1)  {
		for (int i = 0; i <= n; i++) {
			fa[i] = i;
			val[i] = 0;
		}
	}
	int get(int x) {
		if (fa[x] == x) return x;
		int root = get(fa[x]);
		val[x] = (val[x] + val[fa[x]]) % 2;
		return fa[x] = root;
	}
	void merge(int a, int b, int t) {
		int aa = get(a), bb = get(b);
		if (aa == bb) return;
		val[aa] = (t - val[a] + val[b] + 2) % 2;
		fa[aa] = bb;
		return;
	}
	vector<int> fa, val;
};
struct Data {
	int a, b, c;
};
int main() {
	int n, m;
	cin >> n >> m;
	UnionSet u(n);
	vector<Data> arr(m);
	for (int i = 0; i < m; i++) {
		cin >> arr[i].a >> arr[i].b >> arr[i].c;
	}
	sort(arr.begin(), arr.end(), [&](const Data i, const Data j)->bool {
		return i.c > j.c;
		});
	for (int i = 0; i < m; i++) {
		int a = arr[i].a, b = arr[i].b;
		if (u.get(a) == u.get(b)) {
			if ((u.val[a] + u.val[b]) % 2 == 0) {
				cout << arr[i].c;
				return 0;
			}
		}
		else {
			u.merge(a, b, 1);
		}
	}
	cout << 0;
	return 0;
}
相关推荐
binnnngo20 分钟前
Minmax 算法与 Alpha-Beta 剪枝小教学
算法·机器学习·剪枝
এ᭄画画的北北1 小时前
力扣-287.寻找重复数
算法·leetcode
YuTaoShao9 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
小小小新人1212310 小时前
C语言 ATM (4)
c语言·开发语言·算法
你的冰西瓜11 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北11 小时前
力扣-31.下一个排列
算法·leetcode
绝无仅有12 小时前
企微审批对接错误与解决方案
后端·算法·架构
用户50408278583913 小时前
1. RAG 权威指南:从本地实现到生产级优化的全面实践
算法
Python×CATIA工业智造14 小时前
详细页智能解析算法:洞悉海量页面数据的核心技术
爬虫·算法·pycharm