Jupiter Attacks!
Time limit1sMemory limit128 MB
Maintain an array under point updates and queries of a polynomial hash over a subarray modulo a prime, printing each hash result.
- Level
Medium7 of 10
- Topics
- Segment tree, Prefix sum, Math, Implementation
- Solved
- No attempts yet
Problem
Jupiter is invading! Major cities have been destroyed by Jovian spacecraft, and humanity is fighting back. Nlogonia is spearheading the counter-offensive by hacking into the spacecraft's control systems. Unlike Earthling computers, in which a byte usually has possible values, Jovian computers use bytes with possible values, . Nlogonian software engineers have reverse-engineered the firmware of the Jovian spacecraft and plan to sabotage it so that the ships eventually self-destruct.
As a security measure, however, each Jovian spacecraft runs a supervisory program that periodically checks the integrity of the firmware by hashing portions of it and comparing the result against known-good values. To hash the portion of the firmware from the byte at position to the byte at position , the supervisor uses the hash function
where is a prime number. For instance, if and , and bytes to of the firmware have the values , , , and , then
The Nlogonian cryptologists need a way to sabotage the firmware without tripping the supervisor. As a first step, you must write a program that simulates an interleaving of two kinds of commands: editing bytes of the firmware (by the Nlogonian software engineers) and computing hashes of portions of the firmware (by the Jovian supervisory program). At the beginning of the simulation, every byte of the firmware is zero.
Input
The input consists of several test cases. Each test case begins with a line containing four integers , , , and : is the number of possible values of a Jovian byte, is the modulus of the Jovian hash (, with prime), is the length of the firmware in Jovian bytes, and is the number of commands to simulate (). At the start of each test case, every byte is for .
Each of the next lines describes one command. Every command starts with an uppercase letter, either E or H.
E— an edit command, followed by two integers and , meaning that the byte at position (that is, ) must be set to the value ( and ).H— a hash command, followed by two integers and , meaning that must be computed ().
The input ends with a line containing 0 0 0 0, which must not be processed.
Output
For each test case, output the result of every hash command, in order: on the -th line, print an integer, the result of the -th hash command. After each test case, print a line containing a single character - (a hyphen).