Problem solution · Go

Codeforces 891A — Pride

Codeforces 891A — Pride: 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
75 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 891A — Pride, 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

  • 75 lines of Go from the credited upstream file 891A.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 891A — Pride · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"math/bits"	"sort") // github.com/EndlessCheng/codeforces-gotype ST91 [][]int func newST91(a []int) ST91 {	n := len(a)	sz := bits.Len(uint(n))	st := make(ST91, n)	for i, v := range a {		st[i] = make([]int, sz)		st[i][0] = v	}	for j := 1; 1<<j <= n; j++ {		for i := 0; i+1<<j <= n; i++ {			st[i][j] = gcd91(st[i][j-1], st[i+1<<(j-1)][j-1])		}	}	return st} func (st ST91) query(l, r int) int {	k := bits.Len(uint(r-l)) - 1	return gcd91(st[l][k], st[r-1<<k][k])} func CF891A(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n, c1 int	Fscan(in, &n)	a := make([]int, n)	for i := range a {		Fscan(in, &a[i])		if a[i] == 1 {			c1++		}	}	if c1 > 0 {		Fprint(out, n-c1)		return	} 	st := newST91(a)	ans := int(1e9)	for l := range a {		sz := sort.Search(n-l, func(sz int) bool { return st.query(l, l+sz+1) == 1 })		// 注意这里的 sz 实际上要 +1,但是由于只需要取一个相对最小值,+1 可以不写		if sz < n-l && sz < ans {			ans = sz		}	}	if ans == 1e9 {		Fprint(out, -1)	} else {		Fprint(out, ans+n-1)	}} //func main() { CF891A(os.Stdin, os.Stdout) } func gcd91(a, b int) int {	for a != 0 {		a, b = b%a, a	}	return b} 

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 ↗