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;
}
相关推荐
米粒14 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___5 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
漫随流水6 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑7 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub9 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
Titan20249 小时前
map和set的封装学习笔记
数据结构·c++
CoovallyAIHub10 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub10 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki10 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic10 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展