码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1874, dijkstra

时间:2014-10-24 00:01:02      阅读:486      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   java   for   sp   div   on   log   

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();
	}
}

 

hdu 1874, dijkstra

标签:blog   io   ar   java   for   sp   div   on   log   

原文地址:http://www.cnblogs.com/ramanujan/p/4047013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!