Problem solution · Go

Codeforces 1680C — Binary String

Codeforces 1680C — Binary String: a Go solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to EndlessCheng Codeforces Go.

Technique
Binary search
Source
EndlessCheng Codeforces Go
Length
82 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

Binary search

For Codeforces 1680C — Binary String, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 82 lines of Go from the credited upstream file 1680C.go.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

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 1680C — Binary String · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"sort"	"strings") // https://space.bilibili.com/206214func CF1680C(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush()	min := func(a, b int) int {		if a > b {			return b		}		return a	} 	var T int	var s string	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &s)		ans := len(s)		in0 := 0		out1 := strings.Count(s, "1")		left := 0		for _, b := range s {			v := int(b & 1)			in0 += v ^ 1			out1 -= v			for in0 > out1 {				v = int(s[left] & 1)				in0 -= v ^ 1				out1 += v				left++			}			ans = min(ans, out1)		}		Fprintln(out, ans)	}} func CF1680C_binarySearch(_r io.Reader, _w io.Writer) {	in := bufio.NewReader(_r)	out := bufio.NewWriter(_w)	defer out.Flush() 	var T int	var s string	for Fscan(in, &T); T > 0; T-- {		Fscan(in, &s)		n := len(s)		tot1 := strings.Count(s, "1")		Fprintln(out, sort.Search(n, func(mx int) bool {			in0 := 0     // 窗口内的 0 的个数			out1 := tot1 // 窗口外的 1 的个数			left := 0			for _, b := range s {				v := int(b & 1)				in0 += v ^ 1				out1 -= v				for in0 > mx {					v = int(s[left] & 1)					in0 -= v ^ 1					out1 += v					left++				}				if out1 <= mx {					return true				}			}			return false		}))	}} //func main() { CF1680C(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 ↗