Dijkstra 堆优化 JAVA版本

模板基于 P3371 【模板】单源最短路径 

ArrayList模拟的vector第一维开足10000会T,所以只有70分

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Vector;

class Edge implements Comparable{
	int to , cost;
	Edge(int to_,int cost_){
		to = to_;
		cost = cost_;
	}
	@Override
	public int compareTo(Edge o) {
		// TODO Auto-generated method stub
		return this.cost - o.cost;
	}
}
public class Main {
	  
	static int maxn = 1000+10;
	static int[] l;
	static int dis[];
	
	static ArrayList< ArrayList > e;
	public static void dijkstra(int s) {
		int vis[] = new int[maxn];
		dis = new int[maxn];
		for(int i = 0 ; i < maxn ; i++) dis[i] = 2147483647;
		Queue que= new PriorityQueue<>();
		que.add(new Edge(s, 0));
		dis[s] = 0; 
		while(que.isEmpty() == false) {
			Edge now = que.poll();
			int u = now.to;
			if(dis[u] < now.cost)continue;
			if(vis[u] == 1)continue;
			vis[u] = 1;
			for(int i = 0; i < e.get(u).size() ; i++) {
				int next = e.get(u).get(i).to;
				int cost = e.get(u).get(i).cost;
				if(vis[next] == 0 && dis[next] > dis[u] + cost) {
					dis[next] = dis[u] + cost;
					que.add(new Edge(next,dis[next]));
				}
			}
		}
	} 
	 
	public static void main(String args[]) {
		Scanner scan = new Scanner(System.in);
		e = new ArrayList >();
		for(int i = 0 ; i < maxn ; i++) {
			ArrayList temp = new ArrayList();
			e.add(temp);
		}
		int n = scan.nextInt();
		int m = scan.nextInt();
		int s = scan.nextInt(); 
		l = new int[maxn];
		for(int i = 0 ; i < m ; i++) {
			int from = scan.nextInt();
			int to = scan.nextInt();
			int cost = scan.nextInt();	  
			e.get(from).add(new Edge(to,cost));
		}
		dijkstra(s);
		int first = 0;
	    for(int i=1;i<=n;i++) 
	    {
	        if(first > 0)
	            System.out.print(" ");;
	        System.out.print(dis[i]);;
	        first = 1;
	    }
	    System.out.println(); 
	 }
}

 

你可能感兴趣的:(最短路)