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;
}
相关推荐
Tipriest_8 分钟前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法
晨晖21 小时前
顺序查找:c语言
c语言·开发语言·算法
LYFlied1 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
Salt_07282 小时前
DAY44 简单 CNN
python·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
货拉拉技术2 小时前
AI拍货选车,开启拉货新体验
算法
MobotStone2 小时前
一夜蒸发1000亿美元后,Google用什么夺回AI王座
算法
Wang201220132 小时前
RNN和LSTM对比
人工智能·算法·架构
xueyongfu2 小时前
从Diffusion到VLA pi0(π0)
人工智能·算法·stable diffusion
永远睡不够的入3 小时前
快排(非递归)和归并的实现
数据结构·算法·深度优先
cheems95273 小时前
二叉树深搜算法练习(一)
数据结构·算法