백준 2211번: 네트워크 복구

Seungil Kim·2022년 1월 18일
0

PS

목록 보기
141/206

네트워크 복구

백준 2211번: 네트워크 복구

아이디어

문제를 보면 최소 스패닝 트리 문제인가? 싶지만 1번 노드에서 출발할 때 최소 거리를 구하는 문제다. 필요한 간선만 빼고 다 잘라내면, 결국 트리가 된다. 각 노드별로, 자신의 부모 노드가 무엇인지만 기록한다면 어떤 간선을 살려야 하는지 알 수 있다.

코드

#include <bits/stdc++.h>

using namespace std;

constexpr int MAX = 1001, INF = 1e9;
int N, M;
vector<pair<int, int>> adj[MAX]; // cost, node
int dist[MAX], prev_node[MAX];
bool visited[MAX];

void dijkstra() {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    fill(dist, dist+MAX, INF);
    dist[1] = 0;
    pq.push({0, 1});
    while (!pq.empty()) {
        int cost = pq.top().first;
        int cur = pq.top().second;
        pq.pop();
        if (visited[cur]) continue;
        visited[cur] = true;
        for (auto p : adj[cur]) {
            int nc = p.first;
            int next = p.second;
            if (visited[next]) continue;
            if (dist[next] > cost+nc) {
                dist[next] = cost+nc;
                prev_node[next] = cur;
                pq.push({cost+nc, next});
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    cin >> N >> M;
    for (int i = 0; i < M; i++) {
        int a, b, c;
        cin >> a >> b >>c;
        adj[a].push_back({c, b});
        adj[b].push_back({c, a});
    }
    dijkstra();
    cout << N - 1;
    for (int i = 2; i <= N; i++) {
        cout << '\n' << i << ' ' << prev_node[i];
    }
    return 0;
}

여담

문제를 잘 읽도록 하자.

profile
블로그 옮겼어용 https://ks1ksi.io/

2개의 댓글

comment-user-thumbnail
2022년 1월 18일

님 저 42서울 떨어짐 ㅠ

1개의 답글