hdu 1874, dijkstra
import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class Main { private int n, m, s, t, cnt; private int[] head, d; private static final int MAXIMUM = 20000000; private boolean[] done; private Edge[] e; private class Edge{ int val, next, v; public Edge(int val, int next, int v){ this.val = val; this.next = next; this.v = v; } } private class MyComparator<T> implements Comparator<T>{ public int compare(T o1, T o2) { // TODO Auto-generated method stub Pair p1 = (Pair)o1, p2 = (Pair)o2; if(p1.dis > p2.dis) return 1; return p1.dis == p2.dis ? 0 : -1; } } private class Pair{ int dis, node; public Pair(int dis, int node){this.dis=dis; this.node=node;} } private void add(int u, int v, int val){ e[cnt] = new Edge(val, head[u], v); head[u] = cnt++; e[cnt] = new Edge(val, head[v], u); head[v] = cnt++; } private int dijkstra(){ MyComparator<Pair> comparator = new MyComparator<Main.Pair>(); PriorityQueue<Pair> q = new PriorityQueue<Pair>(10,comparator); d = new int[n + 1]; Arrays.fill(d, MAXIMUM); d[s] = 0; done = new boolean[n + 1]; Arrays.fill(done, false); q.add(new Pair(0, s)); while(!q.isEmpty()){ Pair p = q.remove(); if(p.node == t) return d[t] == MAXIMUM ? -1 : d[t]; done[p.node] = true; for(int i = head[p.node]; i != -1; i = e[i].next){ d[e[i].v] = Math.min(d[e[i].v], e[i].val + p.dis); if(!done[e[i].v]) q.add(new Pair(d[e[i].v], e[i].v)); } } return d[t] == MAXIMUM ? -1 : d[t]; } public void hdu1874(){ Scanner sc = new Scanner(System.in); while(sc.hasNext()){ n = sc.nextInt(); m = sc.nextInt(); head = new int[n+1]; cnt = 0; e = new Edge[m << 2]; Arrays.fill(head, -1); for(int i = 0; i < m; i++){ int a = sc.nextInt(), b = sc.nextInt(), val = sc.nextInt(); add(a, b, val); } s = sc.nextInt(); t = sc.nextInt(); System.out.println(dijkstra()); } } public static void main(String[] args) { new Main().hdu1874(); } }