The End of the Pilgrimage
Time limit1sMemory limit1024 MB
Given the last N visited sites, find the expected time until the last N visits are all distinct, printed modulo the prime X.
- Level
Hard8 of 10
- Topics
- Probability, Dynamic programming, Math
- Solved
- No attempts yet
Problem
A pilgrim keeps making a pilgrimage that seems like it will never end. The pilgrim moves from the holy site where they are to another holy site, and each time they arrive at a holy site, they pray to God. They repeat this over and over.
There are holy sites on earth, numbered from 1 to . Moving from holy site to holy site takes exactly minutes. The time to travel between two different holy sites can differ by direction. When the pilgrim arrives at holy site , they pray there for exactly minutes.
After finishing a prayer, the pilgrim moves to the next holy site immediately, following God's revelation. God picks one of the other holy sites, excluding the one where the pilgrim is, with equal probability , and tells the pilgrim. The pilgrim goes there at once. God is almighty and the pilgrim is very quick, so the time between a move and a prayer, or between a prayer and a move, is 0 minutes.
If the last holy sites the pilgrim visited, counted when a prayer ends, are all different, the pilgrimage ends and the pilgrim enters the kingdom God has prepared.
The last holy sites the pilgrim visited are given in order. Find the expected time from the moment the pilgrim finishes praying at their current holy site and starts moving again until the pilgrimage ends.
Input
The first line contains the number of holy sites and a prime (). The use of is explained in the output section.
The second line contains the prayer times (), where is the time spent praying at holy site .
The next lines contain the travel times. The -th of these lines contains (, ).
The next line contains the number of queries ().
Each of the next lines contains positive integers (, ). is the oldest visited holy site, and is the most recently visited one.
Output
Print lines of answers. For every valid input, the expected value is proven to be a rational number.
Let the expected value for the -th visit sequence be the irreducible fraction . On the -th line, print the integer with that satisfies . It is verified that such an exists and is unique for every valid input.