- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 79 lines of Go from the credited upstream file 1147D.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6)7 89type uf47 struct {10 fa, dis []int11 cc int12}13 14func newUnionFind47(n int) uf47 {15 fa := make([]int, n)16 dis := make([]int, n)17 for i := range fa {18 fa[i] = i19 }20 return uf47{fa, dis, n}21}22 23func (u uf47) find(x int) int {24 if u.fa[x] != x {25 root := u.find(u.fa[x])26 u.dis[x] ^= u.dis[u.fa[x]]27 u.fa[x] = root28 }29 return u.fa[x]30}31 32func (u *uf47) merge(from, to, value int) bool {33 x, y := u.find(from), u.find(to)34 if x == y {35 return u.dis[from]^u.dis[to] == value36 }37 u.dis[x] = value ^ u.dis[to] ^ u.dis[from]38 u.fa[x] = y39 u.cc--40 return true41}42 43func cf1147D(in io.Reader, out io.Writer) {44 const mod = 99824435345 s := ""46 Fscan(in, &s)47 n := len(s)48 ans := 049o:50 for st := 1; st < n; st++ {51 u := newUnionFind47(n * 2)52 for i := range n / 2 {53 u.merge(i, n-1-i, 0)54 }55 for i := 1; i < st; i++ {56 if s[i] != '?' && !u.merge(i, 0, int('1'-s[i])) {57 break o58 }59 }60 u.merge(n+st, 0, 0)61 for i, j := st, n-1; i < j; i, j = i+1, j-1 {62 u.merge(n+i, n+j, 0)63 }64 for i := st; i < n; i++ {65 if s[i] != '?' && !u.merge(i, n+i, int(s[i]-'0')) {66 continue o67 }68 }69 m := 170 for range u.cc - st - 1 {71 m = m * 2 % mod72 }73 ans += m74 }75 Fprint(out, ans%mod)76}77 7879