Baekjoon
[#1504] 특정한 최단 경로
강람이
2020. 4. 1. 19:05
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
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <vector>
#include <limits.h>
#include <algorithm>
#include <queue>
using namespace std;
vector<vector<pair<int,int>>> adj;
int n, e;
vector<int> shortestPath(int start, int finish) {
vector<int> dist(n + 1, INT_MAX);
priority_queue<pair<int, int>> pq;
dist[start] = 0;
pq.pop();
for (int i = 0; i < adj[here].size(); i++) {
int there = adj[here][i].first;
int hereThereW = adj[here][i].second;
if (dist[there] > dist[here] + hereThereW) {
dist[there] = dist[here] + hereThereW;
}
}
}
return dist;
}
int main() {
scanf("%d %d", &n, &e);
adj = vector<vector<pair<int, int>>>(n + 1);
for (int i = 0; i < e; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
adj[a].push_back(make_pair(b, c));
adj[b].push_back(make_pair(a, c));
}
int node1, node2; //거쳐야 하는 노드 번호
scanf("%d %d", &node1, &node2);
//min(1->node1->node2->n, 1->node2->node1->n)
int path1 = INT_MAX, path2 = INT_MAX;
vector<int> dist1 = shortestPath(1, n); //dist1[i] = 1에서 i까지의 최단거리
vector<int> distNode1 = shortestPath(node1, n); //distNode1[i] = node1에서 i까지의 최단거리
vector<int> distNode2 = shortestPath(node2, n); //distNode2[i] = node2에서 i까지의 최단거리
if (dist1[node1] != INT_MAX && distNode1[node2] != INT_MAX && distNode2[n] != INT_MAX) {
path1 = dist1[node1] + distNode1[node2] + distNode2[n];
}
if (dist1[node2] != INT_MAX && distNode2[node1] != -INT_MAX && distNode1[n] != INT_MAX) {
path2 = dist1[node2] + distNode2[node1] + distNode1[n];
}
if (path1 == INT_MAX && path2 == INT_MAX) //경로 없으면
printf("-1\n");
else
printf("%d\n", min(path1, path2));
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |