結果
問題 | No.860 買い物 |
ユーザー |
![]() |
提出日時 | 2022-08-25 10:17:34 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 582 ms / 1,000 ms |
コード長 | 2,739 bytes |
コンパイル時間 | 2,070 ms |
コンパイル使用メモリ | 79,548 KB |
実行使用メモリ | 57,700 KB |
最終ジャッジ日時 | 2024-10-12 18:04:39 |
合計ジャッジ時間 | 9,585 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 15 |
ソースコード
import java.io.*;import java.util.*;public class Main {public static void main(String[] args) throws Exception {Scanner sc = new Scanner();int n = sc.nextInt();long total = 0;ArrayList<Path> list = new ArrayList<>();for (int i = 0; i < n; i++) {int c = sc.nextInt();int d = sc.nextInt();if (i > 0) {list.add(new Path(i - 1, i, d));}list.add(new Path(i, n, c));total += c;}Collections.sort(list);UnionFindTree uft = new UnionFindTree(n + 1);for (Path x : list) {if (!uft.same(x)) {uft.unite(x);total += x.value;}}System.out.println(total);}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;}}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 (x == parents[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 x) {return same(x.left, x.right);}public void unite(int x, int y) {parents[find(x)] = find(y);}public void unite(Path x) {unite(x.left, x.right);}}}class Scanner {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer("");public Scanner() throws Exception {}public int nextInt() throws Exception {return Integer.parseInt(next());}public long nextLong() throws Exception {return Long.parseLong(next());}public double nextDouble() throws Exception {return Double.parseDouble(next());}public String next() throws Exception {while (!st.hasMoreTokens()) {st = new StringTokenizer(br.readLine());}return st.nextToken();}}