반응형
https://www.acmicpc.net/problem/1753
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1 ≤ V ≤ 20,000, 1 ≤ E ≤ 300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1 ≤ K ≤ V)가
www.acmicpc.net
#include <bits/stdc++.h>
using namespace std;
int ans[20001], v, e, st;
struct Node {
int n, d;
bool operator<(const Node& b) const {
return d > b.d;
}
};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
fill(ans, ans + 20001, -1);
cin >> v >> e;
cin >> st;
vector<pair<int, int> > m[20001];
for (int i = 0; i < e; i++) {
int a, b, c;
cin >> a >> b >> c;
m[a].push_back({ b,c });
}
priority_queue<Node> Q;
Q.push({ st,0 });
while (!Q.empty()) {
int cur_node = Q.top().n;
int cur_dist = Q.top().d;
Q.pop();
if (ans[cur_node] == -1) {
ans[cur_node] = cur_dist;
for (int i = 0; i < m[cur_node].size(); i++) {
int nx = m[cur_node][i].first;
if (ans[nx] == -1) {
int nd = m[cur_node][i].second + cur_dist;
Q.push({ nx,nd });
}
}
}
}
for (int i = 1; i <= v; i++) {
if (ans[i] == -1) cout << "INF\n";
else cout << ans[i] << '\n';
}
return 0;
}
우선순위큐 최소힙을 이용해
다익스트라 알고리즘으로 풀 수 있다.

반응형
'Algorithm > problem' 카테고리의 다른 글
백준 15971번: 두 로봇 C++ 문제풀이코드 (0) | 2022.02.13 |
---|---|
백준 2636번 : 치즈 BFS C++ (0) | 2022.02.13 |
백준 3111번 : 검열 - deque 활용 코드 C++ (0) | 2022.02.12 |
백준 2042번 : 구간 합 구하기 - Segment Tree C++ (0) | 2022.02.11 |
백준 9935번 : 문자열 폭발 - C++ 스택 직접 구현 (0) | 2022.02.10 |