Given a permutation P and queries K, find the exponent T such that P^T is the K-th smallest among P^1 through P^(M-1) in lexicographic order.
Hard8MathCombinatoricsSortingImplementationNo attempts yetTime limit2sMemory limit512 MBA permutation P of size N is an array P=[P1,P2,…,PN] with 1≤Pi≤N and Pi=Pj for i=j.
For permutations A and B of size N, A is smaller than B when there is an index i (1≤i≤N) such that Ai<Bi and Aj=Bj for all 1≤j<i.
For permutations A and B of size N, the product A×B is the permutation of size N whose i-th entry is (A×B)i=ABi.
For a permutation P and a positive integer z, the power Pz is defined by P1=P and Pz=Pz−1×P for z>1.
You are given a permutation P of size N. Let M be the smallest integer greater than 1 with PM=P. Let A1,A2,…,AM−1 be P1,P2,…,PM−1 sorted in increasing lexicographic order, so A1<A2<⋯<AM−1.
For instance, if P=[2,3,1,5,4] then P1=[2,3,1,5,4], P2=[3,1,2,4,5], P3=[1,2,3,5,4], P4=[2,3,1,4,5], P5=[3,1,2,5,4], P6=[1,2,3,4,5] and P7=[2,3,1,5,4]. Hence M=7 and the sorted array is A=[P6,P3,P4,P1,P2,P5].
You are also given Q queries. The i-th query contains an integer Ki. The answer is the integer Ti (1≤Ti<M) with PTi=AKi. Answer all queries.
The first line contains two integers N and Q (1≤N≤100, 1≤Q≤300000), the size of the permutation and the number of queries. The second line contains N integers P1,P2,…,PN (1≤Pi≤N), the permutation. The input is guaranteed to be a permutation. Each of the next Q lines contains one integer Ki (1≤Ki<M), the query. Here M is the smallest integer greater than 1 with PM=P as defined above, and it is not given explicitly in the input.
Print Q lines, each containing one integer Ti, the answer to the i-th query.
The permutation used in the visible input is the same as the permutation described in the statement.