1일1알

백준 1939번 중량제한 C++ 본문

알고리즘

백준 1939번 중량제한 C++

영춘권의달인 2022. 9. 13. 10:22

출처 : https://www.acmicpc.net/problem/1939

 

유니온 파인드

 

#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;
}

'알고리즘' 카테고리의 다른 글

백준 3273번 두 수의 합 C++  (0) 2022.09.15
백준 2437번 저울 C++  (1) 2022.09.14
백준 17478번 재귀함수가 뭔가요? C++  (0) 2022.09.12
백준 5972번 택배 배송 C++  (0) 2022.09.10
백준 1253번 좋다 C++  (0) 2022.09.09