Approach
Depth-first search
For Codeforces 455C — Civilization, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 73 lines of Go from the credited upstream file 455C.go.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 "bufio"5 . "fmt"6 "io"7)8 9func cf455C(in io.Reader, _w io.Writer) {10 out := bufio.NewWriter(_w)11 defer out.Flush()12 var n, m, q, op, x, y int13 Fscan(in, &n, &m, &q)14 g := make([][]int, n+1)15 for ; m > 0; m-- {16 Fscan(in, &x, &y)17 g[x] = append(g[x], y)18 g[y] = append(g[y], x)19 }20 21 d := make([]int, n+1)22 fa := make([]int, n+1)23 for i := range fa {24 fa[i] = i25 }26 find := func(x int) int {27 rt := x28 for fa[rt] != rt {29 rt = fa[rt]30 }31 for fa[x] != rt {32 fa[x], x = rt, fa[x]33 }34 return rt35 }36 37 for i := 1; i <= n; i++ {38 if fa[i] != i {39 continue40 }41 var dfs func(int, int) int42 dfs = func(x, from int) (maxL int) {43 fa[x] = i44 for _, y := range g[x] {45 if y != from {46 subL := dfs(y, x) + 147 d[i] = max(d[i], maxL+subL)48 maxL = max(maxL, subL)49 }50 }51 return52 }53 dfs(i, 0)54 }55 56 for ; q > 0; q-- {57 Fscan(in, &op, &x)58 if op == 1 {59 Fprintln(out, d[find(x)])60 continue61 }62 Fscan(in, &y)63 x = find(x)64 y = find(y)65 if x != y {66 d[x] = max(d[x], d[y], (d[x]+1)/2+(d[y]+1)/2+1)67 fa[y] = x68 }69 }70}71 7273