結果

問題 No.1054 Union add query
ユーザー tentententen
提出日時 2020-08-20 18:51:07
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,636 ms / 2,000 ms
コード長 2,198 bytes
コンパイル時間 2,180 ms
コンパイル使用メモリ 77,176 KB
実行使用メモリ 66,660 KB
最終ジャッジ日時 2024-04-21 17:40:45
合計ジャッジ時間 17,142 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 105 ms
39,924 KB
testcase_01 AC 117 ms
40,608 KB
testcase_02 AC 111 ms
41,044 KB
testcase_03 AC 1,580 ms
61,468 KB
testcase_04 AC 1,636 ms
65,456 KB
testcase_05 AC 1,541 ms
61,296 KB
testcase_06 AC 1,589 ms
62,884 KB
testcase_07 AC 1,473 ms
62,832 KB
testcase_08 AC 1,531 ms
61,828 KB
testcase_09 AC 1,521 ms
66,660 KB
testcase_10 AC 1,353 ms
65,164 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 q = sc.nextInt();
        UnionFindTree uft = new UnionFindTree(n);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < q; i++) {
            int type = sc.nextInt();
            int a = sc.nextInt();
            int b = sc.nextInt();
            if (type == 1) {
                uft.unite(a - 1, b - 1);
            } else if (type == 2) {
                uft.add(a - 1, b);
            } else {
                sb.append(uft.get(a - 1)).append("\n");
            }
        }
        System.out.print(sb);
    }
    
    static class UnionFindTree {
        int[] parents;
        int[] depth;
        int[] values;
        
        public UnionFindTree(int size) {
            parents = new int[size];
            depth = new int[size];
            values = new int[size];
            for (int i = 0; i < size; i++) {
                parents[i] = i;
                depth[i] = 1;
            }
        }
        
        public int find(int x) {
            if (x == parents[x]) {
                return x;
            } else {
                return find(parents[x]);
            }
        }
        
        public void add(int x, int y) {
            values[find(x)] += y;
        }
        
        public int get(int x) {
            if (x == parents[x]) {
                return values[x];
            } else {
                return values[x] + get(parents[x]);
            }
        }
        
        public boolean same(int x, int y) {
            return find(x) == find(y);
        }
        
        public void unite(int x, int y) {
            int xx = find(x);
            int yy = find(y);
            if (xx == yy) {
                return;
            }
            if (depth[xx] >= depth[yy]) {
                parents[yy] = xx;
                depth[xx] += depth[yy];
                values[yy] -= values[xx];
            } else {
                parents[xx] = yy;
                depth[yy] += depth[xx];
                values[xx] -= values[yy];
            }
        }
    }
} 
0