結果

問題 No.1054 Union add query
ユーザー 37zigen37zigen
提出日時 2019-11-09 02:22:52
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,727 ms / 2,000 ms
コード長 1,498 bytes
コンパイル時間 2,519 ms
コンパイル使用メモリ 75,064 KB
実行使用メモリ 73,672 KB
最終ジャッジ日時 2023-08-18 17:16:21
合計ジャッジ時間 18,087 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 125 ms
55,444 KB
testcase_01 AC 132 ms
55,404 KB
testcase_02 AC 123 ms
56,272 KB
testcase_03 AC 1,722 ms
65,264 KB
testcase_04 AC 1,727 ms
73,672 KB
testcase_05 AC 1,652 ms
65,056 KB
testcase_06 AC 1,644 ms
67,244 KB
testcase_07 AC 1,573 ms
67,608 KB
testcase_08 AC 1,671 ms
67,444 KB
testcase_09 AC 1,689 ms
69,756 KB
testcase_10 AC 1,343 ms
70,732 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.*;
import java.util.*;
import java.math.*;

public class Main {

	class DJSet {
		int n;
		int[] upper;
		long[] weight;

		public DJSet(int n) {
			this.n = n;
			upper = new int[n];
			weight = new long[n];
			Arrays.fill(upper, -1);
		}

		void add_weight(int x, long w) {
			x = root(x);
			weight[x] += w;
		}

		long get_weight(int x) {
			return weight[x] + (upper[x] < 0 ? 0 : get_weight(upper[x]));
		}

		int root(int x) {
			return upper[x] < 0 ? x : root(upper[x]);
		}

		boolean equiv(int x, int y) {
			return root(x) == root(y);
		}

		void setUnion(int x, int y) {
			x = root(x);
			y = root(y);
			if (x == y)
				return;
			if (upper[x] < upper[y]) {
				x ^= y;
				y ^= x;
				x ^= y;
			}
			upper[y] += upper[x];
			upper[x] = y;
			weight[x] -= weight[y];
		}
	}

	void run() {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int Q = sc.nextInt();
		DJSet ds = new DJSet(N);
		PrintWriter pw = new PrintWriter(System.out);
		for (int q = 0; q < Q; ++q) {
			int T = sc.nextInt();
			int A = sc.nextInt();
			int B = sc.nextInt();
			--A;
			if (T == 1) {
				--B;
				if (ds.equiv(A, B))
					continue;
				ds.setUnion(A, B);
			} else if (T == 2) {
				ds.add_weight(A, B);
			} else if (T == 3) {
				pw.println(ds.get_weight(A));
			}
		}
		pw.close();
	}

	public static void main(String[] args) throws FileNotFoundException {
		new Main().run();
	}

	void tr(Object... objects) {
		System.out.println(Arrays.deepToString(objects));
	}
}
0