알고리즘
백준 1939번 중량제한 C++
영춘권의달인
2022. 9. 13. 10:22
유니온 파인드
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
#include <bitset>
using namespace std;
using int64 = long long;
int n, m;
struct Info {
int start;
int end;
int weight;
bool operator<(const Info& other) const {
return weight < other.weight;
}
bool operator>(const Info& other) const {
return weight > other.weight;
}
};
vector<int> parent;
vector<int> height;
vector<Info> infos;
int GetParent(int n) {
if (parent[n] == n) return n;
return parent[n] = GetParent(parent[n]);
}
void Merge(int u, int v) {
u = GetParent(u);
v = GetParent(v);
if (u == v) return;
if (height[u] > height[v])
::swap(u, v);
parent[u] = v;
if (height[u] == height[v])
height[v]++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
parent = vector<int>(n + 1);
height = vector<int>(n + 1, 1);
for (int i = 1; i <= n; i++) parent[i] = i;
for (int i = 0; i < m; i++) {
int start, end, weight;
cin >> start >> end >> weight;
infos.push_back({ start,end,weight });
}
sort(infos.begin(), infos.end(), greater<Info>());
int u, v;
cin >> u >> v;
int ans = 1000000001;
for (auto a : infos) {
if (GetParent(u) == GetParent(v)) break;
Merge(a.start, a.end);
ans = min(ans, a.weight);
}
cout << ans;
}