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;
}
相关推荐
重生之后端学习17 分钟前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展
aini_lovee24 分钟前
严格耦合波(RCWA)方法计算麦克斯韦方程数值解的MATLAB实现
数据结构·算法·matlab
安特尼41 分钟前
推荐算法手撕集合(持续更新)
人工智能·算法·机器学习·推荐算法
鹿角片ljp1 小时前
力扣14.最长公共前缀-纵向扫描法
java·算法·leetcode
Remember_9931 小时前
【数据结构】深入理解优先级队列与堆:从原理到应用
java·数据结构·算法·spring·leetcode·maven·哈希算法
偷星星的贼111 小时前
C++中的状态机实现
开发语言·c++·算法
程序员敲代码吗1 小时前
C++中的组合模式实战
开发语言·c++·算法
52Hz1182 小时前
二叉树理论、力扣94.二叉树的中序遍历、104.二叉树的最大深度、226.反转二叉树、101.对称二叉树
python·算法·leetcode
Shirley~~2 小时前
leetcode移除元素
javascript·数据结构·算法
普贤莲花2 小时前
新生2026年1月20日---星期二(大寒)
程序人生·算法·leetcode