Problem solution · Go

Codeforces 1523D — Love-Hate

Codeforces 1523D — Love-Hate: 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
56 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 1523D — Love-Hate, 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

  • 56 lines of Go from the credited upstream file 1523D.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 1523D — Love-Hate · GoGo
Use this to learn the idea, then write your own version.
package main import (	"bufio"	. "fmt"	"io"	"math/bits"	"math/rand"	"time") // github.com/EndlessCheng/codeforces-gofunc CF1523D(_r io.Reader, out io.Writer) {	t0 := time.Now()	rand.Seed(t0.UnixNano())	in := bufio.NewReader(_r)	var n, m, p, mx int	var ans uint64	Fscanln(in, &n, &m, &p)	low := (n + 1) / 2	a := make([]uint64, n)	for i := range a {		Fscanf(in, "%b\n", &a[i])	}	for time.Since(t0) < 2*time.Second {		// 由于答案是某个元素的子集,且该子集至少出现在一半的元素中,则可以任取一元素作为 mask		// 循环 k 次后,答案不在 mask 中的概率是 0.5^k,非常小		// 然后统计 mask 的所有子集在 a 中的出现次数		// 这里的技巧是,统计 a[i]&mask 的出现次数,然后再据此统计 a[i]&mask 的子集的出现次数		mask := a[rand.Intn(n)]		if bits.OnesCount64(mask) <= mx {			continue		}		cnt := map[uint64]int{}		for _, v := range a {			cnt[v&mask]++		}		cnt2 := map[uint64]int{}		for v, c := range cnt {			for s := v; s > 0; s = (s - 1) & v {				cnt2[s] += c			}		}		for v, c := range cnt2 {			if c >= low {				if o := bits.OnesCount64(v); o > mx {					ans, mx = v, o				}			}		}	}	Fprintf(out, "%0*b", m, ans)} //func main() { CF1523D(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 ↗