반응형
https://www.acmicpc.net/problem/14284
14284번: 간선 이어가기 2
정점 n개, 0개의 간선으로 이루어진 무방향 그래프가 주어진다. 그리고 m개의 가중치 간선의 정보가 있는 간선리스트가 주어진다. 간선리스트에 있는 간선 하나씩 그래프에 추가해 나갈 것이다.
www.acmicpc.net
[ 문제풀이 ]
1. dijkstra를 활용하여 s부터 t까지 이동합니다.
2. 이동거리를 출력합니다.
[ 소스코드 ]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include<iostream> #include<vector> #include<queue> using namespace std; int n, m, s, t; vector<pair<int, int>> list[5001]; int visited[5001]; int main() { scanf("%d %d", &n, &m); fill(visited, visited + n + 1, 987654321); for (int i = 0; i < m; i++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); list[a].push_back({ b,c }); list[b].push_back({ a,c }); } scanf("%d %d", &s, &t); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; pq.push({ 0,s }); while (!pq.empty()) { const int cur = pq.top().second; const int dist = pq.top().first; pq.pop(); if (cur == t) { printf("%d", dist); return 0; } if (visited[cur] < dist) continue; visited[cur] = dist; for (auto& next : list[cur]) { const int nextNode = next.first; const int nextDist = next.second; if (visited[nextNode] > dist + nextDist) { visited[nextNode] = dist + nextDist; pq.push({ visited[nextNode], nextNode }); } } } } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 13905번 - 세부 (C++) (0) | 2023.03.05 |
---|---|
[ 백준 ] 5972번 - 택배 배송 (C++) (0) | 2023.03.04 |
[ 백준 ] 17396번 - 백도어 (C++) (0) | 2023.03.02 |
[ 백준 ] 3066번 - 브리징 시그널 (C++) (0) | 2023.03.01 |
[ 백준 ] 2660번 - 회장뽑기 (C++) (0) | 2023.02.28 |