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 and call it the state of a substring. The -th bit of is 1 if the digit occurred odd times in the string, and 0 otherwise.
We go through all substrings for all and use a map to count how many times a state occurs in those substrings. Any substring is happy if the states of and are identical.
To count the number of all happy substrings, we just have to consider all states. For each state that occurred times, there are ways to map any two of them and to get a happy substring . The total number of all happy substrings is then .
Implementation
Time Complexity: , where 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 stateint curState = 0;// states[i] := # of occurrences of state i in the substrings [0, j]
Python
S = input()# the current statecur_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] += 1for 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!