Table of Contents

ExplanationImplementation

Official Analysis

Explanation

A string is happy if and only if the number of each digit in the string is divisible by 2. Let's represent this information using an integer ii and call it the state of a substring. The kk-th bit of ii is 1 if the digit kk occurred odd times in the string, and 0 otherwise.

We go through all substrings [0,j][0, j] for all jSj \leq |S| and use a map states\text{states} to count how many times a state occurs in those substrings. Any substring [l,r][l, r] is happy if the states of [0,l1][0, l - 1] and [0,r][0, r] are identical.

To count the number of all happy substrings, we just have to consider all states. For each state that occurred xx times, there are x(x1)2\frac{x(x-1)}{2} ways to map any two of them [0,j1][0, j_1] and [0,j2][0, j_2] to get a happy substring [j11,j2][j_1 - 1, j_2]. The total number of all happy substrings is then i210states[i](states[i]1)2\sum_i^{2^{10}} \frac{\text{states}[i] \cdot (\text{states}[i] - 1)}{2}.

Implementation

Time Complexity: O(S+2D)\mathcal{O}(|S| + 2^D), where D=10D = 10 is the number of possible digits in the string.

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
string S;
cin >> S;
// the current state

Java

import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String S = br.readLine();
// the current state
int curState = 0;
// states[i] := # of occurrences of state i in the substrings [0, j]

Python

S = input()
# the current state
cur_state = 0
# states[i] := # of occurrences of state i in the substrings [0, j]
states = [0 for i in range(1 << 10)]
states[cur_state] += 1
for digit in S:
# update the parity of the current digit

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!