AtCoder Beginner Contest - Multiple of 2019
Authors: Maggie Liu, Brad Ma, Mohammad Nour Massri, David Zhang
Explanation
In order to store sections of the string, we can make a suffix array , such that:
For example, if our string was and the modulus was (instead of for the sake of simplicity), the suffix array would be
Keep in mind, that an empty suffix with is also considered.
This is useful because we can access any substring in time through a range query. So if and , this means or .
It also means that if both (both suffixes have the same remainders), subtracting would lead to , meaning a substring that is divisible by .
So with , . Because they substract to zero, it means the substring from index to leads to a number divisible by the modulus. (The substring is which is divisble by 3).
However, we would still need to go through every pair of possible suffixes which would be .
Instead, we do not need to know which suffix has a certain remainder, but rather how many suffixes have that certain remainder.
To elaborate, we can take , and choose 2 numbers that are divisible by the same remainder of 2019, where the amount of times a certain remainder occurs, and 2 (because we are picking 2 indicies and ).
Therefore, our answer is the counts of all the remainders in an array from and .
So in our example with , our new array would look like this:
Where each index represents the count of a certain remainder.
- There are suffixes with a remainder of when dividing by ,
- There are suffixes with a remainder of when dividing by ,
- And there are no suffixes with a remainder of
So, the sum of all of these numbers would be
If , it should be , since there aren't enough suffixes that can make a pair.
Implementation
A prefix array can be utilized as well, but a suffix array is easier to implement.
Errichto's Video
Implementation
Time Complexity:
C++
#include <iostream>using namespace std;int main() {string s;cin >> s;int num = 0, n = s.size(), pow = 1;// initializes array with initializer list// explained here: https://www.learncpp.com/cpp-tutorial/arrays-part-ii/int count[2019]{1};
Java
import java.io.*;import java.util.*;public class MultipleOf2019 {public static void main(String[] args) {Kattio io = new Kattio();String numberString = io.next();int num = 0;int stringLength = numberString.length();int pow = 1;
Python
MOD = 2019string = input()count = [0] * MODcount[0] = 1cur_num = 0power = 1for c in reversed(string):# find the remainder of the current number MOD 2019
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!