有 N 个村庄,编号 1 到 N。
村庄之间有 M 条无向道路,第 i 条道路连接村庄 ai 和村庄 bi,长度是 ci。
所有村庄都是连通的。
共有 K 个村庄有商店,第 j 个有商店的村庄编号是 xj。
然后给出 Q 个询问,第 k 个询问给出一个村庄的编号 yk,问该村庄距离最近的商店有多远?
输入格式
第一行包含两个整数 N,M。
接下来 M 行,每行包含三个整数 ai,bi,ci,表示第 i 条道路连接村庄 ai 和村庄 bi,长度是 ci。
再一行包含整数 K。
接下来 K 行,每行包含一个整数 xj,表示第 j 个有商店的村庄编号是 xj。
再一行包含整数 Q。
接下来 Q 行,每行包含一个整数 yk,表示询问编号为 yk 的村庄与其距离最近的商店之间的距离。
输出格式
对于每个询问,输出该询问的结果。
数据范围
2≤N≤
1
0
5
10^5
105,
N−1≤M≤
m
i
n
(
N
(
N
−
1
)
/
2
,
1
0
5
)
min(N(N−1)/2,10^5)
min(N(N−1)/2,105),
1≤Q≤
1
0
5
10^5
105,
1≤K≤N,
1≤ci≤10000
输入样例:
7 7
1 2 5
1 4 3
2 3 2
2 5 1
3 6 7
5 6 8
6 7 6
3
7
5
4
7
1
2
3
4
5
6
7
输出样例:
3
1
3
0
0
6
0
- 创建虚拟源点 + 堆优化Dijkstra
import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static int n, m, idx = 0, INF = 0x3f3f3f3f;
static class Edge {
private int v, w, ne;
public Edge(int v, int w, int ne) {
this.v = v;
this.w = w;
this.ne = ne;
}
}
static Edge[] edges;
static int[] h, dist;
static boolean[] st;
static class Vertex {
private int ver, dis;
public Vertex(int ver, int dis) {
this.ver = ver;
this.dis = dis;
}
}
public static void main(String[] args) throws IOException {
String[] line = br.readLine().split(" ");
n = Integer.parseInt(line[0]);
m = Integer.parseInt(line[1]);
edges = new Edge[m * 3];
h = new int[n + 1];
dist = new int[n + 1];
st = new boolean[n + 1];
Arrays.fill(h, -1);
while (m-- > 0) {
line = br.readLine().split(" ");
int u = Integer.parseInt(line[0]), v = Integer.parseInt(line[1]), w = Integer.parseInt(line[2]);
add(u, v, w);
add(v, u, w);
}
int k = Integer.parseInt(br.readLine());
while (k-- > 0) {
int x = Integer.parseInt(br.readLine());
add(0, x, 0);
}
dijkstra();
int q = Integer.parseInt(br.readLine());
while (q-- > 0) {
int x = Integer.parseInt(br.readLine());
out.println(dist[x]);
}
br.close();
out.close();
}
public static void add(int u, int v, int w) {
edges[idx] = new Edge(v, w, h[u]);
h[u] = idx++;
}
public static void dijkstra() {
Arrays.fill(dist, INF);
dist[0] = 0;
PriorityQueue<Vertex> heap = new PriorityQueue<>((v1, v2) -> v1.dis - v2.dis);
heap.offer(new Vertex(0, 0));
while (!heap.isEmpty()) {
Vertex t = heap.poll();
if (st[t.ver]) continue;
st[t.ver] = true;
for (int i = h[t.ver]; i != -1; i = edges[i].ne) {
int v = edges[i].v, w = edges[i].w;
if (t.dis + w < dist[v]) {
dist[v] = t.dis + w;
heap.offer(new Vertex(v, dist[v]));
}
}
}
}
}