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;
}
相关推荐
如竟没有火炬6 分钟前
全排列——交换的思想
开发语言·数据结构·python·算法·leetcode·深度优先
寂静山林19 分钟前
UVa 12526 Cellphone Typing
算法
kyle~1 小时前
C++---嵌套类型(Nested Types)封装与泛型的基石
开发语言·c++·算法
sali-tec1 小时前
C# 基于halcon的视觉工作流-章48-短路断路
开发语言·图像处理·人工智能·算法·计算机视觉
墨染点香2 小时前
LeetCode 刷题【128. 最长连续序列】
算法·leetcode·职场和发展
被AI抢饭碗的人2 小时前
算法题(240):最大食物链计数
算法
熬了夜的程序员2 小时前
【LeetCode】82. 删除排序链表中的重复元素 II
数据结构·算法·leetcode·链表·职场和发展·矩阵·深度优先
欧克小奥2 小时前
Floyd判圈算法(Floyd Cycle Detection Algorithm)
算法·floyd
熬了夜的程序员3 小时前
【LeetCode】83. 删除排序链表中的重复元素
算法·leetcode·链表
胖咕噜的稞达鸭3 小时前
AVL树手撕,超详细图文详解
c语言·开发语言·数据结构·c++·算法·visual studio