結果

問題 No.860 買い物
ユーザー htensaihtensai
提出日時 2020-05-14 10:53:35
言語 Java21
(openjdk 21)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,854 bytes
コンパイル時間 2,119 ms
コンパイル使用メモリ 74,872 KB
実行使用メモリ 76,072 KB
最終ジャッジ日時 2023-10-13 03:16:40
合計ジャッジ時間 15,121 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 124 ms
55,948 KB
testcase_01 AC 122 ms
56,188 KB
testcase_02 AC 122 ms
56,060 KB
testcase_03 AC 123 ms
55,960 KB
testcase_04 AC 130 ms
56,024 KB
testcase_05 AC 140 ms
55,796 KB
testcase_06 AC 259 ms
60,040 KB
testcase_07 AC 986 ms
72,744 KB
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 AC 883 ms
74,028 KB
testcase_12 AC 867 ms
71,724 KB
testcase_13 TLE -
testcase_14 TLE -
testcase_15 AC 818 ms
69,004 KB
testcase_16 TLE -
testcase_17 AC 842 ms
75,272 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	public static void main (String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] prices = new int[n];
		int[] costs = new int[n];
		UnionFindTree uft = new UnionFindTree(n + 1);
		PriorityQueue<Path> queue = new PriorityQueue<>();
		long total = 0;
		for (int i = 0; i < n; i++) {
		    int p = sc.nextInt();
		    total += p;
		    queue.add(new Path(i, n, p));
		    int c = sc.nextInt();
		    if (i > 0) {
		        queue.add(new Path(i - 1, i, c));
		    }
		}
		while (queue.size() > 0) {
		    Path p = queue.poll();
		    if (!uft.same(p)) {
		        uft.unite(p);
		        total += p.value;
		    }
		}
		System.out.println(total);
	}
	
	static class UnionFindTree {
	    int[] parents;
	    
	    public UnionFindTree(int size) {
	        parents = new int[size];
	        for (int i = 0; i < size; i++) {
	            parents[i] = i;
	        }
	    }
	    
	    public int find(int x) {
	        if (parents[x] == x) {
	            return x;
	        } else {
	            return parents[x] = find(parents[x]);
	        }
	    }
	    
	    public boolean same(int x, int y) {
	        return find(x) == find(y);
	    }
	    
	    public boolean same(Path p) {
	        return same(p.left, p.right);
	    }
	    
	    public void unite(int x, int y) {
	        if (!same(x, y)) {
	            parents[find(y)] = find(x);
	        }
	    }
	    
	    public void unite(Path p) {
	        unite(p.left, p.right);
	    }
	}
	
	static class Path implements Comparable<Path> {
	    int left;
	    int right;
	    int value;
	    
	    public Path(int left, int right, int value) {
	        this.left = left;
	        this.right = right;
	        this.value = value;
	    }
	    
	    public int compareTo(Path another) {
	        return value - another.value;
	    }
	}
}
0