Official Editorial (C++, Java)
Explanation
Lets consider a string with a non-reduced ratio and a substring with ratio . If we take out the substring with ratio , we are left with another substring with ratio (), therefore making the original string able to be split. Thus, in order to "cut" a substring out of the original string, the reduced ratio of the substring must be the same as the reduced ratio of the original strng.
Note that the substrings must start from index . If we pull a substring out of the middle of the string, it is harder to compute the ratio of the elements before it.
Keep track of the total number of 'D's and total number of 'K's. For each prefix, the ratio of in lowest terms is . The solution to each prefix is how many times this reduced ratio has appeared so far plus one. We add one because the amount of times this reduced ratio appeared is the amount of splits, and the amount of pieces resulting from the splits is the splits plus one.
Implementation
Time Complexity:
C++
#include <algorithm>#include <iostream>#include <unordered_map>#include <vector>using std::cout;using std::endl;using std::vector;int main() {
Java
import java.io.*;import java.util.*;public class DilucKaeya {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));int testNum = Integer.parseInt(read.readLine());StringBuilder ans = new StringBuilder();for (int t = 0; t < testNum; t++) {
Python
from math import gcdfor _ in range(int(input())):input()k_num = 0d_num = 0max_pref_chunks = []pref_ratios = {}for c in input():if c == "D":
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!