-
Notifications
You must be signed in to change notification settings - Fork 3
/
CCC09S4_PriorityQueue.java
73 lines (71 loc) · 2.59 KB
/
CCC09S4_PriorityQueue.java
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* CCC '09 S4 - Shop and Ship
* Question type: Graph Theory
* 3/5 on DMOJ, case 4, 5 tle
* @author Tommy Pang
*/
public class CCC09S4_PriorityQueue {
static StringTokenizer st;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static List<edge>[] adj;
static int [] prices, dis;
static boolean [] vis;
//Priority Queue way
public static void main(String[] args) throws IOException {
int N = Integer.parseInt(br.readLine());
adj = new ArrayList[N+1]; prices = new int[N+1]; dis = new int[N+1];
vis = new boolean[N+1];
Arrays.fill(prices, -1); Arrays.fill(dis, Integer.MAX_VALUE);
for (int i = 0; i <= N; i++) adj[i] = new ArrayList<>();
int T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken()), b = Integer.parseInt(st.nextToken()), c = Integer.parseInt(st.nextToken());
adj[a].add(new edge(b, c)); adj[b].add(new edge(a, c));
}
int K = Integer.parseInt(br.readLine());
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
prices[Integer.parseInt(st.nextToken())] = Integer.parseInt(st.nextToken());
}
int D = Integer.parseInt(br.readLine());
Dijkstra(D);
int ans = Integer.MAX_VALUE;
for (int i = 1; i <= N; i++) {
if (vis[i] && prices[i] != -1){
ans = Math.min(ans, prices[i] + dis[i]);
}
}
System.out.println(ans);
}
static void Dijkstra(int i){
PriorityQueue<edge> queue = new PriorityQueue<>();
queue.add(new edge(i, 0)); dis[i] = 0;
while (!queue.isEmpty()){
edge e = queue.poll();
int b = e.b, cost = e.c;
vis[b] = true;
if (cost>dis[e.b]) continue;
for (edge nxt : adj[b]) {
if (dis[nxt.b] > dis[b] + nxt.c){
dis[nxt.b] = dis[b] + nxt.c;
queue.add(new edge(nxt.b, dis[nxt.b]));
}
}
}
}
public static class edge implements Comparable<edge>{
int b, c;
edge(int end, int cost){
b = end; c = cost;
}
@Override
public int compareTo(edge e) {
return Integer.compare(c, e.c);
}
}
}