PS/BOJ
[알고리즘] 백준 9694번: 무엇을 아느냐가 아니라 누구를 아느냐가 문제다 (C++)
도비(Doby)
2021. 12. 15. 04:16
https://www.acmicpc.net/problem/9694
9694번: 무엇을 아느냐가 아니라 누구를 아느냐가 문제다
맨위 첫 번째 줄에 T(1 <T< 100)는 테스트케이스 수를 의미한다. 이것을 따라 다음줄에 각 테스트 케이스가 주어지는데, 첫 번째 줄에는 N과 M이 주어진다. N(N ≤ 20)은 관계의 개수를 의미하며, M(5 ≤
www.acmicpc.net
양방향 그래프로 0에서 시작하는 다익스트라를 돌려주면 된다.
경로를 담아내는 방법은
(https://draw-code-boy.tistory.com/144)
다음과 같이 경로 역추적의 방식으로 해주면 된다.
[AC 코드]
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
#include <stack>
#define MAX 20 + 1
#define INF 987654321
#define pii pair<int, int>
using namespace std;
int n, m;
int T;
vector<pii> graph[MAX];
//vector<pii> trace[MAX];
int trace[MAX];
struct cmp {
bool operator()(pii& a, pii& b) {
return a.second > b.second;
}
};
vector<int> dijkstra(int node) {
priority_queue<pii, vector<pii>, cmp> pq;
vector<int> dist(20 + 1, INF);
dist[node] = 0;
pq.push({ node, 0 });
while (!pq.empty()) {
int now = pq.top().first;
int cost = pq.top().second;
pq.pop();
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;
//trace[next].clear();
//trace[next].push_back({ now, dist[next] });
}
else if (cost + nextCost == dist[next]) {
//trace[next].push_back({ now, dist[next] });
}
}
}
return dist;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> T;
for (int t = 0; t < T; t++) {
cin >> n >> m;
for (int i = 0; i < n; i++) {
int x, y, w;
cin >> x >> y >> w;
graph[x].push_back({ y, w });
graph[y].push_back({ x, w });
}
cout << "Case #";
cout << t + 1 << ": ";
vector<int> temp = dijkstra(0);
if (temp[m - 1] == INF) cout << -1 << '\n';
else {
stack<int> s;
int node = m - 1;
s.push(node);
while (s.top() != 0) {
node = trace[node];
s.push(node);
}
while (!s.empty()) {
cout << s.top() << ' ';
s.pop();
}
cout << '\n';
}
//init
for (int i = 0; i <= 20; i++) {
graph[i].clear();
//trace[i].clear();
trace[i] = 0;
}
}
return 0;
}