結果

問題 No.1065 電柱 / Pole (Easy)
ユーザー hiromi_ayase
提出日時 2020-05-29 21:41:13
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,939 ms / 2,000 ms
コード長 2,296 bytes
コンパイル時間 3,080 ms
コンパイル使用メモリ 79,496 KB
実行使用メモリ 97,644 KB
最終ジャッジ日時 2024-11-06 03:06:36
合計ジャッジ時間 58,598 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();
        int x = sc.nextInt() - 1;
        int y = sc.nextInt() - 1;

        int[][] p = new int[n][];
        for (int i = 0; i < n; i++) {
            p[i] = new int[] { sc.nextInt(), sc.nextInt() };
        }

        int[] from = new int[m];
        int[] to = new int[m];
        int[] w = new int[m];
        for (int i = 0; i < m; i ++) {
            from[i] = sc.nextInt() - 1;
            to[i] = sc.nextInt() - 1;
            
            int dx = p[from[i]][0] - p[to[i]][0];
            int dy = p[from[i]][1] - p[to[i]][1];
            w[i] = dx * dx + dy * dy;
        }

        int[][][] g = packWU(n, from, to, w);
        double[] d = dijk(g, x);
        System.out.println(d[y]);
    }

	public static int[][][] packWU(int n, int[] from, int[] to, int[] w){ return packWU(n, from, to, w, from.length); }
	public static int[][][] packWU(int n, int[] from, int[] to, int[] w, int sup)
	{
		int[][][] g = new int[n][][];
		int[] p = new int[n];
		for(int i = 0;i < sup;i++)p[from[i]]++;
		for(int i = 0;i < sup;i++)p[to[i]]++;
		for(int i = 0;i < n;i++)g[i] = new int[p[i]][2];
		for(int i = 0;i < sup;i++){
			--p[from[i]];
			g[from[i]][p[from[i]]][0] = to[i];
			g[from[i]][p[from[i]]][1] = w[i];
			--p[to[i]];
			g[to[i]][p[to[i]]][0] = from[i];
			g[to[i]][p[to[i]]][1] = w[i];
		}
		return g;
    }
    

    public static double[] dijk(int[][][] g, int from)
	{
		int n = g.length;
		final double[] td = new double[n];
		Arrays.fill(td, Integer.MAX_VALUE);
		TreeSet<Integer> q = new TreeSet<Integer>(new Comparator<Integer>(){
			public int compare(Integer a, Integer b) {
				if(td[a] - td[b] != 0)return Double.compare(td[a], td[b]);
				return a - b;
			}
		});
		q.add(from);
		td[from] = 0;
		
		while(q.size() > 0){
			int cur = q.pollFirst();
			
			for(int i = 0;i < g[cur].length;i++){
				int next = g[cur][i][0];
				double nd = td[cur] + Math.sqrt(g[cur][i][1]);
				if(nd < td[next]){
					q.remove(next);
					td[next] = nd;
					q.add(next);
				}
			}
		}
		
		return td;
	}
}
0