Firepersons

Time limit1sMemory limit128 MB

Summary
Given the first k terms and multipliers of a linear recurrence modulo 10000, return the i-th term for i up to 10^9.
Level

Medium7 of 10

Topics
Math, Matrix, Divide and conquer, Implementation
Solved
No attempts yet

Problem

Each fireperson is given an integer rank, and these ranks come from an integer sequence defined as follows.

A sequence of order kk is defined by its first kk terms a0,a1,…,ak−1a_0, a_1, \dots, a_{k-1} and by integer constants b1,b2,…,bkb_1, b_2, \dots, b_k. For n≥kn \ge k, the terms follow the recurrence

an=(∑i=1kan−i bi) mod 10000.a_n = \left(\sum_{i=1}^{k} a_{n-i}\, b_i\right) \bmod 10000.

The ii-th oldest fireperson receives rank aia_i. Given the parameters of the sequence and an integer ii, compute the rank of the ii-th fireperson, that is, the ii-th term aia_i of the sequence.

Input

The input consists of several test cases. Each test case is given on a single line containing the following integers separated by single spaces, in order:

ka0 … ak−1b1 … bkik \quad a_0 \ \dots \ a_{k-1} \quad b_1 \ \dots \ b_k \quad i

  • 1≤k≤1001 \le k \le 100 : the order of the sequence
  • 0≤aj<100000 \le a_j < 10000 : the first kk terms of the sequence
  • 0≤bj<100000 \le b_j < 10000 : the multipliers of the recurrence
  • 0≤i<1 000 000 0000 \le i < 1\,000\,000\,000 : the index of the requested term

The input ends with a line containing a single 00.

Output

For each test case, print on its own line the ii-th term aia_i of the corresponding sequence. The output lines must appear in the same order as the test cases in the input.

Examples7

  1. Example 1

    Input
    2 0 1 1 1 6
    0
    
    Expected output
    8
    
  2. Example 2

    Input
    2 0 1 1 1 20
    0
    
    Expected output
    6765
    
  3. Example 3

    Input
    3 5 7 9 1 1 1 0
    3 5 7 9 1 1 1 2
    0
    
    Expected output
    5
    9
    
  4. Example 4

    Input
    3 1 2 3 1 1 1 3
    0
    
    Expected output
    6
    
  5. Example 5

    Input
    2 9999 9999 9999 9999 5
    0
    
    Expected output
    2
    
  6. Example 6

    Input
    1 7 3 5
    0
    
    Expected output
    1701
    
  7. Example 7

    Input
    3 1 2 3 0 0 1 6
    0
    
    Expected output
    1