Problem solution · Go

Codeforces 1062F — Upgrading Cities

Codeforces 1062F — Upgrading Cities: a Go solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Direct simulation
Source
EndlessCheng Codeforces Go
Length
70 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Codeforces 1062F — Upgrading Cities, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 70 lines of Go from the credited upstream file 1062F.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from EndlessCheng Codeforces Go by Σndless (EndlessCheng) and is used under the MIT licence.

Full codeCodeforces 1062F — Upgrading Cities · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF1062F(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n, m, v, w, ans int	Fscan(in, &n, &m)	g := make([][]int, n)	deg := make([]int, n)	rg := make([][]int, n)	rdeg := make([]int, n)	for ; m > 0; m-- {		Fscan(in, &v, &w)		v--		w--		g[v] = append(g[v], w)		deg[w]++		rg[w] = append(rg[w], v)		rdeg[v]++	} 	cnt := make([]int, n)	topo := func(g [][]int, deg []int) {		cntTo := n		q := []int{}		for i, d := range deg {			if d == 0 {				q = append(q, i)				cntTo--			}		}		for len(q) > 0 {			v, q = q[0], q[1:]			if len(q) == 0 {				cnt[v] += cntTo // 如果队列为空,那么 v 可以到达后面所有的节点			} else if len(q) == 1 { // 如果队列只剩一个节点,那么判断删去该节点后 v 能否到达后面所有的节点				for _, w := range g[q[0]] {					if deg[w] == 1 { // 肥肠抱歉,存在一个可以从 q[0] 达到的点						goto o					}				}				cnt[v] += cntTo			}		o:			for _, w := range g[v] {				if deg[w]--; deg[w] == 0 {					q = append(q, w)					cntTo--				}			}		}	}	topo(g, deg)	topo(rg, rdeg)	for _, c := range cnt {		if c >= n-2 {			ans++		}	}	Fprint(out, ans)} //func main() { CF1062F(os.Stdin, os.Stdout) } 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗