Problem solution · Go

Codeforces 1083A — The Fair Nut and the Best Path

Codeforces 1083A — The Fair Nut and the Best Path: 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
55 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 1083A — The Fair Nut and the Best Path, 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

  • 55 lines of Go from the credited upstream file 1083A.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 1083A — The Fair Nut and the Best Path · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF1083A(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	max := func(a, b int64) int64 {		if a > b {			return a		}		return b	} 	var n, v, w, wt int	Fscan(in, &n)	a := make([]int, n)	for i := range a {		Fscan(in, &a[i])	}	type nb struct{ to, wt int }	g := make([][]nb, n)	for i := 1; i < n; i++ {		Fscan(in, &v, &w, &wt)		v--		w--		g[v] = append(g[v], nb{w, wt})		g[w] = append(g[w], nb{v, wt})	} 	ans := int64(0)	var f func(int, int) int64	f = func(v, fa int) int64 {		mx := int64(a[v])		ans = max(ans, mx)		for _, e := range g[v] {			if w := e.to; w != fa {				if m := f(w, v) - int64(e.wt); m >= 0 {					ans = max(ans, mx+m)        // 拼接来自两棵不同子树的路径					mx = max(mx, m+int64(a[v])) // 更新子树路径的最大值				}			}		}		return mx	}	f(0, -1)	Fprint(out, ans)} //func main() { CF1083A(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 ↗