Problem solution · Go

Codeforces 1725L — Lemper Cooking Competition

Codeforces 1725L — Lemper Cooking Competition: a Go solution using segment tree or range structure. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Segment tree or range structure
Source
EndlessCheng Codeforces Go
Length
59 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

Segment tree or range structure

For Codeforces 1725L — Lemper Cooking Competition, the implementation stores interval information in a range-query data structure so updates and queries avoid rescanning the full input.

  1. Choose the aggregate stored for each interval or prefix.
  2. Build or initialize the structure from the input.
  3. Apply updates and combine the affected nodes to answer each query.

Code notes

  • 59 lines of Go from the credited upstream file 1725L.go.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the build once, then multiply the logarithmic update or query path by the number of operations.

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 1725L — Lemper Cooking Competition · GoGo
Use this to learn the idea, then write your own version.
package main import (	. "fmt"	"io"	"slices"	"sort") // https://github.com/EndlessChengtype fenwick []int func (t fenwick) add(i int) {	for ; i < len(t); i += i & -i {		t[i]++	}} func (t fenwick) pre(i int) (res int) {	for ; i > 0; i &= i - 1 {		res += t[i]	}	return} func cf1725L(in io.Reader, out io.Writer) {	var n int	Fscan(in, &n)	s := make([]int, n+1)	for i := 1; i <= n; i++ {		Fscan(in, &s[i])		s[i] += s[i-1]	}	if s[n] < 0 {		Fprint(out, -1)		return	}	for i := 1; i < n; i++ {		if s[i] < 0 || s[i] > s[n] {			Fprint(out, -1)			return		}	} 	b := slices.Clone(s[1:])	slices.Sort(b) 	ans := 0	t := make(fenwick, n+1)	for i := 1; i < n; i++ {		x := sort.SearchInts(b, s[i]) + 1		ans += i - 1 - t.pre(x)		t.add(x)	}	Fprint(out, ans)} //func main() { cf1725L(bufio.NewReader(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 ↗