- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 52 lines of Go from the credited upstream file 1552D.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.
Use this to learn the idea, then write your own version.
1package main2 3import (4 . "fmt"5 "io"6)7 8/*9由于 j 和 k 没有顺序关系10我们可以将 a 中的部分元素取反,记其为 a'11设 b[0]=0,构造 b 为 a'[:n-1] 的前缀和12若 a'[:n-1] 中存在一个子区间,其区间和等于 a'[n-1]13由于 b 就是 a'[:n-1] 的前缀和,所以 a'[n-1] 也能用 b 的两个元素相减表示14所以 a' 需要满足 a'[l]+...+a'[r] = a'[n-1]15移项得 a'[l]+...+a'[r] - a'[n-1] = 016实际上,由于 a' 元素的顺序没有关系,这其实就是 a' 的一个子集,其元素和为 017因此得出结论:需要在 a 中找到一个子集,该子集的部分元素取反后,能够使该子集元素和为 0,若能找到这样的子集则输出 YES,否则输出 NO18 19进一步地,我们只需要判断 a 中是否存在两个子集和相等就行了20设这两个子集为 A 和 B,则有 A[0]+A[1]+... = B[0]+B[1]+...21移项得 A[0]+A[1]+... -B[0]-B[1]-... = 022注意,若两个子集有相同的元素,会在上式中消去23消去后的剩余部分就是 a 的一个子集,其中部分元素取反24*/25 2627func CF1552D(in io.Reader, out io.Writer) {28 var T, n int29 for Fscan(in, &T); T > 0; T-- {30 Fscan(in, &n)31 a := make([]int, n)32 for i := range a {33 Fscan(in, &a[i])34 }35 has := map[int]bool{}36 for i := 0; i < 1<<n; i++ {37 sum := 038 for j, v := range a {39 sum += i >> j & 1 * v40 }41 has[sum] = true42 }43 if len(has) < 1<<n {44 Fprintln(out, "YES")45 } else {46 Fprintln(out, "NO")47 }48 }49}50 5152