728x90

https://www.acmicpc.net/problem/1238
1238번: 파티
첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X가 공백으로 구분되어 입력된다. 두 번째 줄부터 M+1번째 줄까지 i번째 도로의 시작점, 끝점, 그리고 이 도로를 지나는데 필요한 소요시간 Ti가 들어
www.acmicpc.net
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
86
87
88
89
90
91
92
93
94
95
96
97
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int N, M, X;
static List<List<Info>> map, remap;
static boolean[] visit;
static int[] distance;
static int[] me_to_there, there_to_me;
static PriorityQueue<Info> pq;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
X = Integer.parseInt(st.nextToken());
map = new ArrayList<>();
remap = new ArrayList<>();
for(int i=0;i<N+1;i++){
map.add(new ArrayList<>());
remap.add(new ArrayList<>());
}
for(int i=0;i<M;i++){
st = new StringTokenizer(br.readLine());
int to = Integer.parseInt(st.nextToken());
int from = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
map.get(to).add(new Info(from, w));
remap.get(from).add(new Info(to, w));
}
me_to_there = dijkstra(map);
there_to_me = dijkstra(remap);
int answer = 0;
for(int i=1;i<=N;i++){
answer = Math.max(answer, me_to_there[i]+there_to_me[i]);
}
System.out.println(answer);
}
public static int[] dijkstra(List<List<Info>> maps){
visit = new boolean[N+1];
distance = new int[N+1];
pq = new PriorityQueue<>();
for(int i=1;i<=N;i++){
distance[i] = 1000001;
}
pq.add(new Info(X, 0));
distance[X] =0;
while (!pq.isEmpty()){
int cx = pq.peek().V;
pq.poll();
if(visit[cx]) continue;
visit[cx] = true;
for(int i=0;i<maps.get(cx).size();i++){
int nx = maps.get(cx).get(i).V;
int nweight = maps.get(cx).get(i).weight;
if(distance[nx] > distance[cx]+nweight){
distance[nx] = distance[cx]+nweight;
pq.add(new Info(nx, distance[nx]));
}
}
}
return distance;
}
public static class Info implements Comparable<Info>{
int V, weight;
public Info(int v, int weight) {
V = v;
this.weight = weight;
}
@Override
public int compareTo(Info o) {
return this.weight-o.weight;
}
}
}
|
cs |
[풀이]
각 노드끼리의 간선들은 단방향이고, 단방향 노드이지만 어느 지점에서 시작하던지 '시작 노드'로 돌아올 수 있다.
따라서 전환점을 의미하는 노드 X를 기준으로 두 번 다익스트라를 돌리면 된다.
모든 정점에서 X까지의 거리와, X에서 모든 정점까지의 거리를 구한다는 의미로 이해하면 될 것 같다.
잼있었다.

728x90
'알고리즘 > 백준' 카테고리의 다른 글
[Java] 2812 크게 만들기 (0) | 2022.03.29 |
---|---|
[Java] 2573 - 빙산 - BFS, 시뮬레이션 (0) | 2022.03.10 |
[Java] 2606 바이러스 - BFS (0) | 2022.03.10 |
[Java] 과제 - Greedy (0) | 2022.02.08 |
[Java] 1103 게임 - BFS, DP (0) | 2022.02.06 |
댓글