Under construction

Still being built. Things may change

Permutation Cycles and Queries

Time limit7sMemory limit512 MB

Summary
Given a permutation A and a huge exponent m, answer queries that swap two entries of A and print the sum of S^m(i) times i.
Level

Hard8 of 10

Topics
Number theory, Array, Implementation
Solved
No attempts yet

Problem

You are given an array AA of nn distinct integers from 11 to nn, and an integer mm. Define S0(i)=iS^0(i)=i and Sk(i)=A[Sk−1(i)]S^k(i)=A[S^{k-1}(i)] for 1≤k≤m1 \le k \le m and 1≤i≤n1 \le i \le n. There is a list QQ of qq queries about Sm(i)S^m(i). Each query is one of two types.

  • Type 1, 1 i j: swap the values of A[i]A[i] and A[j]A[j].
  • Type 2, 2: print Sm(1)×1+Sm(2)×2+⋯+Sm(n)×nS^m(1) \times 1 + S^m(2) \times 2 + \cdots + S^m(n) \times n.

Process the queries in QQ in order, from the first to the qq-th, and print the result of each type 2 query.

Input

The first line contains nn and mm, separated by a space.

The second line contains the elements A[1],A[2],…,A[n]A[1], A[2], \ldots, A[n], separated by spaces.

The third line contains the number of queries qq.

The next qq lines each contain one query as a sequence of integers separated by spaces.

Output

For each type 2 query, print the result on its own line, in the order the queries appear.

Constraints

  • 1≤n,q≤100,0001 \le n, q \le 100{,}000
  • 1≤m≤101,000−11 \le m \le 10^{1{,}000}-1
  • 1≤A[i]≠A[j]≤n1 \le A[i] \ne A[j] \le n for 1≤i≠j≤n1 \le i \ne j \le n
  • Every query in QQ is type 1 or type 2.
  • QQ contains at least 1 and at most min⁡(q,1,000)\min(q, 1{,}000) type 2 queries.

Hint

SmS^m is the result of applying the move operation to the elements of array AA exactly mm times. Let Sk(i)S^k(i) be the position of the ii-th element after kk moves, so the initial position is S0(i)=iS^0(i)=i, the position after one move is S1(i)=A[i]S^1(i)=A[i], and after mm moves it is Sm(i)=A[Sm−1(i)]S^m(i)=A[S^{m-1}(i)].

For example, let A={2,1,3}A=\{2, 1, 3\} and m=3m=3. For the first element, S0(1)=1S^0(1)=1, S1(1)=A[1]=2S^1(1)=A[1]=2, S2(1)=A[S1(1)]=1S^2(1)=A[S^1(1)]=1, and S3(1)=A[S2(1)]=2S^3(1)=A[S^2(1)]=2. For the second element, S0(2)=2S^0(2)=2, S1(2)=A[2]=1S^1(2)=A[2]=1, S2(2)=A[S1(2)]=2S^2(2)=A[S^1(2)]=2, and S3(2)=A[S2(2)]=1S^3(2)=A[S^2(2)]=1. For the third element, Sk(3)=3S^k(3)=3 for every kk.

Examples1

  1. Example 1

    Input
    4 3
    1 2 3 4
    5
    2
    1 1 2
    2
    1 2 3
    2
    
    Expected output
    30
    29
    30