PS/BOJ
[알고리즘] 백준 2211번: 네트워크 복구 (C++)
도비(Doby)
2021. 12. 7. 16:39
https://www.acmicpc.net/problem/2211
2211번: 네트워크 복구
첫째 줄에 두 정수 N, M이 주어진다. 다음 M개의 줄에는 회선의 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 컴퓨터와 B번 컴퓨터가 통신 시간이 C (1 ≤ C ≤ 10)인 회선으로 연결되어 있다
www.acmicpc.net
이번 문제는 문제의 뜻을 파악하기가 어렵다. (https://yabmoons.tistory.com/444)
우선 최소 몇 개의 회선을 복구해야 하는지는 당연히 1부터 2 ~ N까지 가는 회선의 최소 개수이기 때문에
K = N - 1이다.
1은 슈퍼 컴퓨터이므로 1을 제외한 각 노드들로부터 1로 가는 제일 첫 노드로 가는 간선을 출력해주면 된다.
#include <iostream>
#include <queue>
#include <vector>
#include <utility>
#define pii pair<int, int>
#define MAX 1000 + 1 // n이 될 수 있는 수가 1000이 최대라서 플로이드 와샬은 안 된다.
#define INF 987654321
using namespace std;
vector<pii> graph[MAX];
int n, m;
int trace[MAX];
struct cmp {
bool operator()(pii& a, pii& b) {
return a.second > b.second;
}
};
vector<int> dijkstra(int node) {
vector<int> dist(n + 1, INF);
priority_queue<pii, vector<pii>, cmp> pq;
dist[node] = 0;
pq.push({ node, 0 });
while (!pq.empty()) {
int now = pq.top().first;
int cost = pq.top().second;
pq.pop();
if (dist[now] < cost) {
continue;
}
for (int i = 0; i < graph[now].size(); i++) {
int next = graph[now][i].first;
int nextCost = graph[now][i].second;
if (cost + nextCost < dist[next]) {
dist[next] = cost + nextCost;
pq.push({ next, dist[next] });
trace[next] = now; // 간선 입력
}
}
}
return dist;
}
int main() {
cin >> n >> m;
for (int i = 0, a, b, c; i < m; i++) {
cin >> a >> b >> c;
graph[a].push_back({ b, c });
graph[b].push_back({ a, c });
}
vector<int> dist = dijkstra(1);
cout << n - 1 << '\n';
for (int i = 2; i <= n; i++) {
cout << trace[i] << ' ' << i << '\n';
}
return 0;
}
업 솔빙 필요한 문제