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

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

백준 1197 문제

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
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 visited[SIZE];
ll ans;
vector<pii> graph[SIZE];
priority_queue<pii> pq;

void initInput() {
    cin >> V >> E;

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

void prim() {
    pq.push({0, 1});

    while (!pq.empty()) {
        int curWeight = -pq.top().first;
        int curNode = pq.top().second;
        pq.pop();

        if (visited[curNode]) continue;

        visited[curNode] = true;
        ans += curWeight;

        for (int i = 0; i < graph[curNode].size(); i++) {
            int nextNode = graph[curNode][i].first;
            int nextWeight = graph[curNode][i].second;

            pq.push({-nextWeight, nextNode});
        }
    }
}

void solve() {
    prim();
    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++] kruskal 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++] kruskal 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++] prim algorithm (MST)
상단으로

티스토리툴바