n,m = map(int,input().split()) p = list(range(n + 1))
deffind(x): if p[x]!=x: p[x] = find(p[x]) return p[x]
while m: m = m - 1 arr = input().split() op,a,b = arr[0],int(arr[1]),int(arr[2]) a = find(a) b = find(b) if op == "M": p[a] = b elif op == "Q": if a == b: print("Yes") else: print("No")
classSolution: deffindRedundantConnection(self, edges: List[List[int]]) -> List[int]: n = len(edges) p = list(range(n + 1)) deffind(x): if x != p[x]: p[x] = find(p[x]) return p[x] ans = [] for x,y in edges: a = find(x) b = find(y) if a == b: ans.append([x,y]) continue if a!=b: p[a] = b # 最后的加进去的附加边长 就是在edges中最后出现的边 return ans[-1]
funcfind(x int)int { if p[x] != x { p[x] = find(p[x]) } return p[x] }
funcmain() { n, m := 0, 0 fmt.Scanf("%d %d",&n,&m) // 这里已经转换为二维的并查集了 所以要初始化的值为n*n for i := 0; i < n * n; i++ { p[i] = i }
get := func(x, y int)int { return x*n + y }
flag := false
for i := 1; i <= m; i++ { var x, y int var d string fmt.Scanf("%d %d %s", &x, &y, &d) // 将下标映射到0开始 x-- y-- //fmt.Println(x,y,d) if d == "D" { a := get(x, y) b := get(x+1, y) if find(a) == find(b) { fmt.Println(i) flag = true break } else { p[b] = find(a) } } else { a := get(x, y) b := get(x, y+1) if find(a) == find(b) { fmt.Println(i) flag = true break } else { p[b] = find(a) } } }
var f = make([]int, N) var w = make([]int, N) var v = make([]int, N) var p = make([]int, N)
funcfind(x int)int { if x != p[x] { p[x] = find(p[x]) } return p[x] }
funcmain() { var n, m, money int fmt.Scanf("%d %d %d", &n, &m, &money)
for i := 1; i <= n; i++ { fmt.Scanf("%d %d", &v[i], &w[i]) p[i] = i }
max := func(a, b int)int { if a > b { return a } return b }
for i := 0; i < m; i++ { var a, b int fmt.Scanf("%d %d", &a, &b) pa := find(a) pb := find(b) if pa == pb { continue } v[pb] += v[pa] w[pb] += w[pa] p[pa] = pb }
for i := 1; i <= n; i++ { if p[i] == i { for j := money; j >= v[i]; j-- { f[j] = max(f[j], f[j-v[i]]+w[i]) } } }