Problem solution · Go

Codeforces 1548B — Integers Have Friends

Codeforces 1548B — Integers Have Friends: 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
63 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 1548B — Integers Have Friends, 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

  • 63 lines of Go from the credited upstream file 1548B.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 1548B — Integers Have Friends · 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-gofunc CF1548B(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	abs := func(x int64) int64 {		if x < 0 {			return -x		}		return x	}	gcd := func(a, b int64) int64 {		for a != 0 {			a, b = b%a, a		}		return b	}	max := func(a, b int) int {		if a > b {			return a		}		return b	} 	var T, n int	var pre, v int64	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &n, &pre)		n--		st := make([][18]int64, n)		for i := range st {			Fscan(in, &v)			st[i][0] = abs(v - pre)			pre = v		}		for j := 1; 1<<j <= n; j++ {			for i := 0; i+1<<j <= n; i++ {				st[i][j] = gcd(st[i][j-1], st[i+1<<(j-1)][j-1])			}		} 		ans := 1		for r := 1; r <= n; r++ {			// 或者双指针 https://codeforces.com/contest/1548/submission/124638948			l := sort.Search(r, func(l int) bool { k := bits.Len(uint(r-l)) - 1; return gcd(st[l][k], st[r-1<<k][k]) > 1 })			ans = max(ans, r-l+1)		}		Fprintln(out, ans)	}} //func main() { CF1548B(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 ↗