結果

問題 No.860 買い物
ユーザー htensaihtensai
提出日時 2020-05-14 10:51:24
言語 Java21
(openjdk 21)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,854 bytes
コンパイル時間 2,300 ms
コンパイル使用メモリ 75,352 KB
実行使用メモリ 77,080 KB
最終ジャッジ日時 2023-10-13 03:13:13
合計ジャッジ時間 16,849 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 127 ms
55,792 KB
testcase_01 AC 126 ms
55,800 KB
testcase_02 AC 129 ms
55,724 KB
testcase_03 AC 127 ms
56,012 KB
testcase_04 AC 138 ms
56,012 KB
testcase_05 AC 148 ms
55,824 KB
testcase_06 AC 268 ms
60,012 KB
testcase_07 AC 995 ms
71,000 KB
testcase_08 TLE -
testcase_09 TLE -
testcase_10 TLE -
testcase_11 AC 901 ms
71,452 KB
testcase_12 AC 887 ms
74,428 KB
testcase_13 TLE -
testcase_14 TLE -
testcase_15 AC 845 ms
77,080 KB
testcase_16 TLE -
testcase_17 AC 861 ms
71,068 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(x)] = find(y);
	        }
	    }
	    
	    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