Problem solution · Go

Codeforces 1117D — Magic Gems

Codeforces 1117D — Magic Gems: 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
65 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 1117D — Magic Gems, 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

  • 65 lines of Go from the credited upstream file 1117D.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 1117D — Magic Gems · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"slices") // https://github.com/EndlessChengconst mod17 = 1_000_000_007 func kitamasa17(coef, a []int, n int) (ans int) {	defer func() { ans = (ans%mod17 + mod17) % mod17 }()	if n < len(a) {		return a[n]	} 	k := len(coef)	compose := func(a, b []int) []int {		c := make([]int, k)		for _, v := range a {			for j, w := range b {				c[j] = (c[j] + v*w) % mod17			}			bk1 := b[k-1]			for j := k - 1; j > 0; j-- {				b[j] = (b[j-1] + bk1*coef[j]) % mod17			}			b[0] = bk1 * coef[0] % mod17		}		return c	} 	resC := make([]int, k)	resC[0] = 1	c := make([]int, k)	c[1] = 1	for ; n > 0; n /= 2 {		if n%2 > 0 {			resC = compose(c, resC)		}		c = compose(c, slices.Clone(c))	} 	for i, c := range resC {		ans = (ans + c*a[i]) % mod17	}	return} func cf1117D(in io.Reader, out io.Writer) {	var n, m int	Fscan(in, &n, &m)	a := make([]int, m)	for i := range a {		a[i] = 1	}	coef := make([]int, m)	coef[0] = 1	coef[m-1] = 1	Fprint(out, kitamasa17(coef, a, n))} //func main() { cf1117D(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 ↗