結果

問題 No.2290 UnUnion Find
ユーザー ynm3nynm3n
提出日時 2023-05-05 23:58:09
言語 Go
(1.22.1)
結果
RE  
実行時間 -
コード長 1,821 bytes
コンパイル時間 13,101 ms
コンパイル使用メモリ 219,380 KB
実行使用メモリ 11,648 KB
最終ジャッジ日時 2024-05-02 19:09:36
合計ジャッジ時間 17,832 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 RE -
testcase_01 RE -
testcase_02 RE -
testcase_03 TLE -
testcase_04 -- -
testcase_05 -- -
testcase_06 -- -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
testcase_28 -- -
testcase_29 -- -
testcase_30 -- -
testcase_31 -- -
testcase_32 -- -
testcase_33 -- -
testcase_34 -- -
testcase_35 -- -
testcase_36 -- -
testcase_37 -- -
testcase_38 -- -
testcase_39 -- -
testcase_40 -- -
testcase_41 -- -
testcase_42 -- -
testcase_43 -- -
testcase_44 -- -
testcase_45 -- -
testcase_46 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)
	defer wr.Flush()

	var n, q int
	fmt.Fscan(rd, &n, &q)

	uf := newUnionFindTree(n)
	var typ, u, v int
	for i := 0; i < q; i++ {
		fmt.Fscan(rd, &typ)
		switch typ {
		case 1:
			fmt.Fscan(rd, &u, &v)
			u--
			v--
			uf.unite(u, v)
		case 2:
			fmt.Fscan(rd, &v)
			r := uf.findRoot(v)
			ans := -1
			for v2 := range uf.roots {
				if r != v2 {
					ans = v2 + 1
					break
				}
			}
			fmt.Fprintln(wr, ans)
		}
	}
}

// UnionFind Tree
type unionFindTree struct {
	// 備忘録
	// 根となる頂点の要素には、特別に以下のような数値が格納されています。
	// 「その根が含まれている木」に含まれる頂点の数にマイナスをかけたもの
	parent []int
	// 連結成分の個数です
	cnt int

	roots map[int]struct{}
}

func newUnionFindTree(n int) *unionFindTree {
	uf := new(unionFindTree)
	uf.parent = make([]int, n)
	for i := range uf.parent {
		uf.parent[i] = -1
	}
	uf.cnt = n
	uf.roots = make(map[int]struct{})
	for i := 0; i < n; i++ {
		uf.roots[i] = struct{}{}
	}
	return uf
}
func (uf *unionFindTree) findRoot(a int) int {
	if uf.parent[a] < 0 {
		return a
	}
	r := uf.findRoot(uf.parent[a])
	if _, exist := uf.roots[a]; exist && a != r {
		delete(uf.roots, a)
	}
	uf.parent[a] = r
	return r
}
func (uf *unionFindTree) unite(a, b int) bool {
	x, y := uf.findRoot(a), uf.findRoot(b)
	if x == y {
		return false
	}
	if uf.size(x) < uf.size(y) {
		x, y = y, x
	}
	delete(uf.roots, y)
	uf.parent[x] += uf.parent[y]
	uf.parent[y] = x
	uf.cnt--
	return true
}
func (uf *unionFindTree) sameRoot(a, b int) bool {
	return uf.findRoot(a) == uf.findRoot(b)
}
func (uf *unionFindTree) size(a int) int {
	return -uf.parent[uf.findRoot(a)]
}
0