- 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
- 87 lines of Go from the credited upstream file 501E.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 89func cf501E(in io.Reader, out io.Writer) {10 var n, odd int11 Fscan(in, &n)12 a := make([]int, n)13 tot := make([]int, n+1)14 for i := range a {15 Fscan(in, &a[i])16 tot[a[i]]++17 }18 for _, c := range tot {19 odd += c % 220 }21 if odd > 1 {22 Fprint(out, 0)23 return24 }25 26 l := 027 for l < n/2 && a[l] == a[n-1-l] {28 l++29 }30 if l == n/2 {31 Fprint(out, n*(n+1)/2)32 return33 }34 r := n/2 - 135 for a[r] == a[n-1-r] {36 r--37 }38 39 clear(tot)40 cnt := make([]int, n+1)41 for i := l; i <= r; i++ {42 cnt[a[i]]++43 tot[a[i]]++44 tot[a[n-1-i]]++45 }46 bal := true47 for i, c := range cnt {48 if c*2 != tot[i] {49 bal = false50 break51 }52 }53 if bal {54 Fprint(out, (l+1)*(n-r+n-1-r-l))55 return56 }57 58 clear(tot)59 for _, v := range a[l : n-l] {60 tot[v]++61 }62 63 clear(cnt)64 rr := n - 1 - l65 for ; ; rr-- {66 v := a[rr]67 cnt[v]++68 if cnt[v] > tot[v]/2 {69 break70 }71 }72 73 clear(cnt)74 ll := l75 for ; ; ll++ {76 v := a[ll]77 cnt[v]++78 if cnt[v] > tot[v]/2 {79 break80 }81 }82 83 Fprint(out, (l+1)*(n-rr+ll-l))84}85 8687