abmnk

Time limit: 0.2s Memory limit: 2MB Input: abmnk.in Output: abmnk.out

You are given the numbers PP, mm, nn, kk, and two sequences: b1,b2,bmb_1, b_2, \dots b_m and a0,a1,an1a_0, a_1, \dots a_{n-1} of natural numbers. The sequence v0,v1,,vn1v_0, v_1, \dots , v_{n-1} is formed by traversing the elements of aa from kk to k(modn)k \pmod{n}, starting from position 0.

Each number in vv is replaced with the closest natural power of an element from bb. If a number is equidistant from two powers, the smaller value is chosen. For example, if b=[2,3]b = [2, 3], the powers of the elements in sequence bb are: 1,2,4,8,16,,1,3,9,27,81,1, 2, 4, 8, 16, \dots, 1, 3, 9, 27, 81, \dots.

Task

  1. If P=1P = 1, find the sum of the values in the sequence vv after the replacements.
  2. If P=2P = 2, when a number is less than the chosen power, it will be replaced with the negative of the chosen power (For example, instead of 5, it would be -5). Then calculate SS by traversing the elements of vv in order (0,1,2,n10, 1, 2, \dots n-1) and applying the formula S=((S*k+v[i])%n+n)%n. Initially, SS=0.

Input data

The first line of the input file abmnk.in contains PP. The second line contains the numbers mm, nn, and kk, in this order, separated by spaces. The third line contains the sequence b1,b2,bmb_1, b_2, \dots b_m of natural numbers greater than or equal to 2, separated by spaces. The fourth line contains the sequence a0,a1,an1a_0, a_1, \dots a_{n-1} of natural numbers separated by spaces.

Output data

The first line of the output file abmnk.out will contain a single integer, the answer to requirement PP.

Constraints and clarifications

  • It is guaranteed that gcd (n,k)=1(n, k) = 1.
  • 1m1 0001 \le m \le 1\ 000
  • 1k<n1 000 0001 \le k < n \le 1\ 000\ 000
  • The numbers in the input file are less than or equal to 10910^9

Subtasks

# Points Constraints
1 11 P=1,1k<n1 000,1m100P = 1, 1 \leq k < n \leq 1\ 000, 1 \leq m \leq 100
2 18 P=1,1k<n1 000 000,1m1 000P = 1, 1 \leq k < n \leq 1\ 000\ 000, 1 \leq m \leq 1\ 000
3 12 P=2,1k<n10 000,1m9P = 2, 1 \leq k < n \leq 10\ 000, 1 \leq m \leq 9
4 7 P=2,1k<n100 000,1m9P = 2, 1 \leq k < n \leq 100\ 000, 1 \leq m \leq 9
5 52 P=2,1k<n1 000 000,1m9P = 2, 1 \leq k < n \leq 1\ 000\ 000, 1 \leq m \leq 9

Example 1

abmnk.in

1
5 15 4
2 32 10000 17 3
5 16 289 57 32 27 70 1 10000000 100000000 4 90 81 1024 531441

abmnk.out

108921736

Explanation

We traverse from 4 to 4 and obtain V={5,32,10000000,81,16,27,100000000,1024,289,70,4,531441,57,1,90}V = \{5, 32, 10000000, 81, 16, 27, 100000000, 1024, 289, 70, 4, 531441, 57, 1, 90\}.

Example 2

abmnk.in

2
5 15 4
2 32 10000 17 3
5 16 289 57 32 27 70 1 10000000 100000000 4 90 81 1024 531441

abmnk.out

8

Explanation

In the end, V={4,32,8388608,81,16,27,100000000,1024,289,64,4,531441,64,1,81}V = \{4, 32, 8388608, 81, 16, 27, 100000000, 1024, 289, 64, 4, 531441, -64, 1, 81\}.

Log in or sign up to be able to send submissions!