結果

問題 No.1065 電柱 / Pole (Easy)
ユーザー tenten
提出日時 2020-08-20 10:30:33
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,979 ms / 2,000 ms
コード長 2,574 bytes
コンパイル時間 2,261 ms
コンパイル使用メモリ 79,752 KB
実行使用メモリ 106,484 KB
最終ジャッジ日時 2024-10-13 03:45:19
合計ジャッジ時間 56,511 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

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;
        Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++) {
            nodes[i] = new Node(i, sc.nextInt(), sc.nextInt());
        }
        HashMap<Node, ArrayList<Node>> graph = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            if (!graph.containsKey(nodes[a])) {
                graph.put(nodes[a], new ArrayList<>());
            }
            graph.get(nodes[a]).add(nodes[b]);
            if (!graph.containsKey(nodes[b])) {
                graph.put(nodes[b], new ArrayList<>());
            }
            graph.get(nodes[b]).add(nodes[a]);
        }
        double[] costs = new double[n];
        Arrays.fill(costs, Double.MAX_VALUE);
        PriorityQueue<Path> queue = new PriorityQueue<>();
        queue.add(new Path(nodes[x], 0));
        while (queue.size() > 0) {
            Path p = queue.poll();
            if (costs[p.node.idx] <= p.value) {
                continue;
            }
            costs[p.node.idx] = p.value;
            for (Node nd : graph.get(p.node)) {
                queue.add(new Path(nd, p.value + p.node.getDistance(nd)));
            }
        }
        System.out.println(costs[y]);
    }
    

    static class Path implements Comparable<Path> {
        Node node;
        double value;

        public Path(Node node, double value) {
            this.node = node;
            this.value = value;
        }
        
        public int compareTo(Path another) {
            if (value == another.value) {
                return 0;
            } else if (value < another.value) {
                return -1;
            } else {
                return 1;
            }
        }
    }
    
    static class Node {
        int idx;
        int x;
        int y;
        
        public Node(int idx, int x, int y) {
            this.idx = idx;
            this.x = x;
            this.y = y;
        }
        
        public double getDistance(Node another) {
            return Math.sqrt(Math.pow(x - another.x, 2) + Math.pow(y - another.y, 2));
        }
        
        public int hashCode() {
            return idx;
        }
        
        public boolean equals(Object o) {
            Node n = (Node)o;
            return idx == n.idx;
        }
    }
} 
0