문제링크 : https://www.acmicpc.net/problem/1238
이 문제는, 다익스트라 알고리즘을 (1번 + 정점의 개수)번 사용하면 되는 문제 입니다.
파티장소인 x장소에서 각 정점으로 가는 길이를 전부 구한 후, 각 정점에서 x로가는 길이를 구하면 되는 문제 입니다.
시간복잡도는 O((n^2) + 1) = O(n^2) 입니다.
소스코드 :
이 문제는, 다익스트라 알고리즘을 (1번 + 정점의 개수)번 사용하면 되는 문제 입니다.
파티장소인 x장소에서 각 정점으로 가는 길이를 전부 구한 후, 각 정점에서 x로가는 길이를 구하면 되는 문제 입니다.
시간복잡도는 O((n^2) + 1) = O(n^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
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
|
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#define INF 987654321
using namespace std;
int main() {
cin.tie(0);
ios_base::sync_with_stdio(false);
int n, m, x;
cin >> n >> m >> x;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq;
vector<vector< pair<int, int> > > graph(n + 1);
vector<int> distance(n + 1, INF);
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
graph[a].push_back({ b,c });
}
// 일단 x에서 역으로 각 마을에 가는 최단거리를 구한다.
pq.push({ 0,x });
// 출발점에서 출발점으로 가는 거리는 0.
distance[x] = 0;
while (!pq.empty()) {
int node = pq.top().second;
int cost = pq.top().first;
pq.pop();
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i].first;
int distanceToNeighbor = graph[node][i].second;
if (cost + distanceToNeighbor < distance[neighbor]) {
distance[neighbor] = cost + distanceToNeighbor;
pq.push({ cost + distanceToNeighbor, neighbor });
}
}
}
int mostLongestDistance = 0;
for (int q = 1; q <= n; q++) {
vector<int> tmpDistance(n + 1, INF);
// q에서의 최단거리를 구한다.
pq.push({ 0, q});
// 출발점에서 출발점으로 가는 거리는 0.
tmpDistance[q] = 0;
while (!pq.empty()) {
int node = pq.top().second;
int cost = pq.top().first;
pq.pop();
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i].first;
int distanceToNeighbor = graph[node][i].second;
if (cost + distanceToNeighbor < tmpDistance[neighbor]) {
tmpDistance[neighbor] = cost + distanceToNeighbor;
pq.push({ cost + distanceToNeighbor, neighbor });
}
}
}
if (tmpDistance[x] + distance[q] > mostLongestDistance) {
mostLongestDistance = tmpDistance[x] + distance[q];
}
}
cout << mostLongestDistance << endl;
}
| cs |
댓글
댓글 쓰기