[C/C++] kruskal algorithm (MST)

2023. 6. 27. 15:10·Computer Science/Algorithm

백준 1197문제

#include <iostream>
#include <tuple>
#include <algorithm>
#include <vector>
using namespace std;
#define PS_INPUT cout.tie(NULL); cin.tie(NULL); ios_base::sync_with_stdio(false)
#define endl '\n'
#define INF 1e9
#define pii pair<int, int>
#define ll long long
#define SIZE 10001

int V, E;
bool check;
ll ans;
int parent[SIZE];
vector<tuple<int, int, int>> graph;

void initInput() {
    cin >> V >> E;
    for (int i = 1; i <= V; i++) parent[i] = i;

    int a, b, c;
    for (int i = 0; i < E; i++) {
        cin >> a >> b >> c;
        graph.push_back({c, a, b});
    }
    sort(graph.begin(), graph.end());
}

int findParent(int x) {
    if (parent[x] == x) return x;
    return parent[x] = findParent(parent[x]);
}

bool unionParent(int v1, int v2) {
    int u = findParent(v1);
    int v = findParent(v2);
    if (u == v) return false;
    else {
        parent[u] = v;
        return true;
    }
}

void kruskal() {
    for (int i = 0; i < E; i++) {
        if (unionParent(get<1>(graph[i]), get<2>(graph[i])))
            ans += get<0>(graph[i]);
    }
}

void solve() {
    kruskal();
    cout << ans << endl;
}

int main(void)
{
    PS_INPUT; 
    initInput();
    solve();

    return 0;
}
저작자표시 (새창열림)

'Computer Science > Algorithm' 카테고리의 다른 글

[C/C++] Topology Sort (graph)  (0) 2023.06.27
[C/C++] prim algorithm (MST)  (0) 2023.06.27
[C/C++] 에라토스테네스의 체  (0) 2023.05.30
[C/C++] BFS(Breadth-First Search)  (0) 2023.05.30
[C/C++] DFS(Depth-First Search)  (0) 2023.05.30
'Computer Science/Algorithm' 카테고리의 다른 글
  • [C/C++] Topology Sort (graph)
  • [C/C++] prim algorithm (MST)
  • [C/C++] 에라토스테네스의 체
  • [C/C++] BFS(Breadth-First Search)
Study with Me!
Study with Me!
Study with Me!
  • Study with Me!
    Seongmo
    Study with Me!
  • 전체
    오늘
    어제
    • Computer (147)
      • Computer Science (61)
        • Data Structure (51)
        • Algorithm (6)
        • 선형대수 with C++ (4)
      • Backend (11)
        • 백엔드 취업을 위해.. (1)
        • Spring (10)
        • Database (0)
        • Testing (0)
        • Infra & DevOps (0)
      • Arm Architecture (1)
        • Register (0)
        • Assembly Instruction (1)
      • Linux (32)
        • Linux Kernel (4)
        • 라이브러리 함수 구현하기 (0)
        • 쉘, 쉘 명령어 구현하기 (15)
        • Ubuntu (13)
      • Cloud Infrastructure (8)
        • Kubernetes (7)
        • OpenStack Magnum (1)
      • AWS (3)
      • Baekjoon (18)
      • Tools (6)
        • Git & Github (5)
        • Vim (1)
      • 개발 환경 (7)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    STL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Study with Me!
[C/C++] kruskal algorithm (MST)
상단으로

티스토리툴바