반응형
https://www.acmicpc.net/problem/5972
풀이
- 기본적인 다익스트라를 적용하면 바로 풀리는 문제이다.
- 따로 조건이 없기 때문에 1에서 n까지 가는 최단경로를 구하면 된다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 98765432;
vector<pair<int, int> > v[50001];
int dist[50001];
void bfs(int a) {
fill(dist, dist + 50001, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> q;
q.emplace(0, a);
dist[a] = 0;
while(!q.empty()) {
int x = q.top().second;
int distSum = q.top().first;
q.pop();
if(dist[x] < distSum) continue;
for(int i=0; i<v[x].size(); i++) {
int nx = v[x][i].first;
int nCost = distSum + v[x][i].second;
if(dist[nx] > nCost) {
q.emplace(nCost, nx);
dist[nx] = nCost;
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for(int i=0; i<m; i++) {
int a, b, c;
cin >> a >> b >> c;
v[a].emplace_back(b, c);
v[b].emplace_back(a, c);
}
bfs(1);
cout << dist[n];
return 0;
}
반응형
'코딩테스트' 카테고리의 다른 글
[c++] 백준 - 20168_골목 대장 호석 - 기능성 (0) | 2024.08.15 |
---|---|
[c++] 백준 - 17396_백도어 (0) | 2024.08.15 |
[c++] 프로그래머스 - n진수 게임 (0) | 2024.08.15 |
[c++] 프로그래머스 - 프렌즈4블록 (0) | 2024.08.15 |
[C++] 프로그래머스 - 이중우선순위큐 (0) | 2024.04.15 |