반응형
https://www.acmicpc.net/problem/23793
23793번: 두 단계 최단 경로 1
서준이는 아빠로부터 생일선물로 세계 지도를 받아서 매우 기뻤다. 세계 지도에서 최단 경로를 찾는 프로그램을 개발해서 아빠께 감사의 마음을 전달하려고 한다. 세계 지도는 도시를 정점으
www.acmicpc.net
[ 문제풀이 ]
1. dijkstra 함수를 만들어서 A에서 B까지 C를 거치지 않았을 때의 거리를 return 합니다.
2. XY, YZ의 거리를 더해 XYZ의 거리를 출력하고, XZ의 Y를 거치지 않았을 때 거리를 출력합니다.
[ 소스코드 ]
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include<iostream> #include<vector> #include<queue> using namespace std; struct node { int to; int dist; }; struct cmp { bool operator()(node right, node left) { return left.dist < right.dist; } }; int N, M; int X, Y, Z; vector<node> list[100001]; int visited[100001]; int dijkstra(int a, int b, int c) { for (int i = 1; i <= N; i++) { visited[i] = 1987654321; } visited[a] = 0; int ret = 0; priority_queue<node, vector<node>, cmp> pq; pq.push({ a,0 }); while (!pq.empty()) { const int cur = pq.top().to; const int dist = pq.top().dist; pq.pop(); if (visited[cur] < dist) continue; if (cur == b) { return dist; } for (auto next : list[cur]) { const int nNode = next.to; const int nDist = next.dist; if (visited[nNode] > nDist + dist && nNode != c) { visited[nNode] = nDist + dist; pq.push({ nNode,visited[nNode] }); } } } return -1; } int main() { scanf("%d %d", &N, &M); for (int i = 0; i < M; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); list[u].push_back({ v, w }); } scanf("%d %d %d", &X, &Y, &Z); int XY = dijkstra(X, Y, 0); int YZ = dijkstra(Y, Z, 0); int XZ = dijkstra(X, Z, Y); if (XY == -1 || YZ == -1) { printf("-1 "); } else { printf("%d ", XY + YZ); } printf("%d", XZ); } | cs |
반응형
'백준' 카테고리의 다른 글
[ 백준 ] 1194번 - 달이 차오른다, 가자. (C++) (0) | 2022.12.28 |
---|---|
[ 백준 ] 2589번 - 보물섬 (C++) (0) | 2022.12.27 |
[ 백준 ] 1759번 - 암호 만들기 (C++) (0) | 2022.12.25 |
[ 백준 ] 19538번 - 루머 (C++) (0) | 2022.12.24 |
[ 백준 ] 1922번 - 네트워크 연결 (C++) (0) | 2022.12.23 |