반응형
https://www.acmicpc.net/problem/1719
문제 해결 알고리즘
모든 노드에서 다익스트라 알고리즘을 쓴다.
거리를 갱신 해줄 때, 전 노드를 배열에 저장해준다.
소스 코드
#include <bits/stdc++.h>
#define MAX_SIZE 201
#define INF 1e9
using namespace std;
vector<pair<int, int>> graph[MAX_SIZE];
int d[MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
void dijkstra(int start_node){
priority_queue<pair<int, int>> pq;
pq.push({0, start_node});
d[start_node] = 0;
while(!pq.empty()){
int dist = -pq.top().first;
int now = pq.top().second;
pq.pop();
if(dist > d[now]) continue;
for(int i=0;i<graph[now].size();i++){
int cost = dist + graph[now][i].first;
if(cost < d[graph[now][i].second]){
d[graph[now][i].second] = cost;
pq.push({-cost, graph[now][i].second});
result[graph[now][i].second][start_node] = now;
}
}
}
}
int main(){
int n, m; cin >> n >> m;
for(int i=0;i<m;i++){
int a, b, c; cin >> a >> b >> c;
graph[a].push_back({c, b});
graph[b].push_back({c, a});
}
for(int i=1;i<=n;i++){
fill(d, d+MAX_SIZE, INF);
dijkstra(i);
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(result[i][j]) cout << result[i][j] << ' ';
else cout << "- ";
}
cout << '\n';
}
}
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[BFS] BOJ 2665 미로만들기 (0) | 2023.02.11 |
---|---|
[DP] BOJ 11054 가장 긴 바이토닉 부분 수열 (C++) (0) | 2022.10.26 |
[DP] BOJ 13398 연속합 2 (C++) (0) | 2022.10.23 |
[그리디] BOJ 12931 두 배 더하기 (C++) (0) | 2022.10.20 |
[0-1 BFS] BOJ 1261 알고스팟 (C++) (0) | 2022.10.17 |