Limited Memory
Time limit7sMemory limit4 MB
Generate a huge pseudorandom array with a linear recurrence and answer many order-statistic queries without storing the array.
- Level
Medium7 of 10
- Topics
- Binary search, Math, Implementation, Sorting
- Solved
- No attempts yet
Problem
An array of integers is defined, but its elements are not given directly. They are generated by the rule below.
Each query is a single integer and asks for the -th smallest element of . The index is 0-based, so asks for the smallest element and for the second smallest. A value that appears several times is counted once per appearance.
This looks easy, because sorting the array and reading off the answers would settle it. The memory limit is too small for that: you cannot hold all of at once. The number of queries is small, so all of the query data does fit.
You are given , , , and the list of queries. The pseudocode that builds is:
X[0] = x0
for i = 1 to N-1:
X[i] = (X[i-1] * a + b) % 1000000007
The intermediate product exceeds 32 bits, so watch out for integer overflow.
Write a program that prints the sum of the answers to all queries.
Input
The first line contains the integers , , and , separated by spaces. (, )
The second line contains the number of queries . ()
The third line contains integers, the queries, separated by spaces. ()
Output
Print the sum of the answers to all queries on one line. The value is smaller than , so it fits in a 64-bit integer.