Problem solution · Go

Codeforces 305C — Ivan and Powers of Two

Codeforces 305C — Ivan and Powers of Two: 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
30 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 305C — Ivan and Powers of Two, 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

  • 30 lines of Go from the credited upstream file 305C.go.
  • The implementation keeps its working state in language-native values and containers.
  • 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 305C — Ivan and Powers of Two · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io") // github.com/EndlessCheng/codeforces-gofunc CF305C(_r io.Reader, out io.Writer) {	in := bufio.NewReader(_r)	var n, v, max int	Fscan(in, &n)	bit := make(map[int]bool, n)	for ; n > 0; n-- {		Fscan(in, &v)		for bit[v] {			delete(bit, v)			v++		}		bit[v] = true		if v > max {			max = v		}	}	Fprint(out, max+1-len(bit))} //func main() { CF305C(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 ↗