static void dijkstra() {
PriorityQueue<PII> q = new PriorityQueue<PII>((a,b) -> (a.x - b.x));
q.add(new PII(0,0));
Arrays.fill(dist,INF);
dist[0] = 0;
while(q.size()>0) {
PII t = q.poll();
int ver = t.y;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[ver] + w[i]) {
dist[j] = dist[ver] + w[i];
q.add(new PII(dist[j],j));
}
}
}
}
例题
import java.util.*;
public class Main {
static int INF = 0x3f3f3f;
static int N = 100005;
static int M = N*3;
static long mod = 1000000007;
//static long[] a = new long[N];
// static int[] vis = new int[N];
// static int[] num = new int[N];
// static int[] diff = new int[N];
static long n;
//static ArrayList<Integer> []lists;
//static long dp[][] = new long [5005][5005];
//static int a[] = new int [N];
static int h[] = new int [N];
static int e[] = new int [M];
static int w[] = new int [M];
static int ne[] = new int [M];
static int dist[] = new int[N];
static boolean st[] = new boolean [N];
static int idx = 0;
static void add(int a,int b,int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
static void dijkstra() {
PriorityQueue<PII> q = new PriorityQueue<PII>((a,b) -> (a.x - b.x));
q.add(new PII(0,0));
Arrays.fill(dist,INF);
dist[0] = 0;
while(q.size()>0) {
PII t = q.poll();
int ver = t.y;
if(st[ver]) continue;
st[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[ver] + w[i]) {
dist[j] = dist[ver] + w[i];
q.add(new PII(dist[j],j));
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for(int i=0;i<N;i++) {
h[i] = -1;
}
while(m-->0) {
int a,b,c;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
add(a, b, c);
add(b, a, c);
}
int k = sc.nextInt();
while(k-->0) {
int x = sc.nextInt();
add(0, x, 0);
}
dijkstra();
int q = sc.nextInt();
while(q-->0) {
int x = sc.nextInt();
System.out.println(dist[x]);
}
sc.close();
}
}
class PII{
int x;
int y;
public PII(int x, int y) {
super();
this.x = x;
this.y = y;
}
public PII() {
}
}