Explanation
First, notice that sequences and can be transformed into a . As an example, we transform to and then simplify into . We can also rearrange any two adjacent characters, like to . As an example, we transform to and then simplify to .
Since we can freely swap characters in a substring, only the frequency of each character is relevant in answering a query.
Let , , and be the frequency of their respective characters in the queried subarray. We can compute these values with prefix sums.
Notice that if or are even, the answer must be false, because we can't simplify the substring into a single without or characters remaining. This is because the parity of or is always constant, beacuse by performing the expansion or deletion operation, we can never change the parity. (For example, -> or -> , both of which hold the same parity of C + W).
To prove that the substring is valid when is odd and is odd, we can first notice that when these two conditions hold, is even.
Next, we simplify and by removing all duplicate pairs. One possibility is that we will be left with and , meaning that was odd, and thus it can easily be simplified into one character.
Otherwise, we will be left with and , meaning that was even. By combining the pair into a singular , we will be left with an odd amount of , which can be simplified into one character.
So, to answer a query, we check if and are both odd. Calculating these values can be done using prefix sums.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {string s;cin >> s;// Calculate prefix array for each charactervector<array<int, 3>> a(s.size() + 1);for (int i = 1; i <= s.size(); i++) {
Python
s = input()n = len(s)# Calculate prefix array for each charactera = [[0, 0, 0] for _ in range(n + 1)]for i, ch in enumerate(s, 1):a[i][0] = a[i - 1][0] + (ch == "C")a[i][1] = a[i - 1][1] + (ch == "O")a[i][2] = a[i - 1][2] + (ch == "W")
Java
import java.io.*;import java.util.StringTokenizer;public class COWOperations {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(System.out);String s = r.readLine();// Calculate the prefix array for each character
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!