PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000095. Sắp xếp nổi bọt trên tiền tố (Prefix Bubble Sort)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Sắp xếp nổi bọt trên tiền tố (Prefix Bubble Sort)

Prefix Bubble Sort

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation P=(P1,P2,…,PN)P=(P_1,P_2,\ldots,P_N) of 1,2,…,N1,2,\ldots,N.

For an integer kk between 22 and NN, operation kk works as follows: visit i=1,2,…,k−1i=1,2,\ldots,k-1 in increasing order. At each step, swap the current PiP_i and Pi+1P_{i+1} if Pi>Pi+1P_i>P_{i+1}; otherwise do nothing. An operation performs exactly one left-to-right pass over the first kk positions, rather than repeatedly sorting the prefix.

You are also given a non-decreasing sequence A1≤A2≤⋯≤AMA_1\le A_2\le\cdots\le A_M, with 2≤Ai≤N2\le A_i\le N. Starting from the initial permutation, execute operations A1,A2,…,AMA_1,A_2,\ldots,A_M in order. After each operation, output the current number of inversions.

An inversion is a pair of positions (i,j)(i,j) with 1≤i<j≤N1\le i<j\le N and Pi>PjP_i>P_j.

Input

Line 1 contains NN. Line 2 contains NN integers P1,…,PNP_1,\ldots,P_N. Line 3 contains MM. Line 4 contains MM integers A1,…,AMA_1,\ldots,A_M in execution order.

Output

Print exactly MM lines. Line ii contains the inversion count after operation AiA_i has completed.

Subtasks

  • Subtask 1 (20 points): 2≤N≤102\le N\le10; 1≤M≤101\le M\le10; PP is a permutation of 1,2,…,N1,2,\ldots,N; 2≤A1≤⋯≤AM≤N2\le A_1\le\cdots\le A_M\le N.
  • Subtask 2 (30 points): 2≤N≤20002\le N\le2000; 1≤M≤20001\le M\le2000; PP is a permutation of 1,2,…,N1,2,\ldots,N; 2≤A1≤⋯≤AM≤N2\le A_1\le\cdots\le A_M\le N.
  • Subtask 3 (50 points): 2≤N≤2⋅1052\le N\le2\cdot10^5; 1≤M≤2⋅1051\le M\le2\cdot10^5; PP is a permutation of 1,2,…,N1,2,\ldots,N; 2≤A1≤⋯≤AM≤N2\le A_1\le\cdots\le A_M\le N.

Examples

Example 1

Input

6
3 2 4 1 6 5
2
4 6

Output

3
1

Explanation

Initially P=(3,2,4,1,6,5)P=(3,2,4,1,6,5). Operation 44 swaps 33 and 22, leaves 33 and 44, then swaps 44 and 11, producing (2,3,1,4,6,5)(2,3,1,4,6,5). Its three inversions are the pairs of values (2,1),(3,1),(6,5)(2,1),(3,1),(6,5), so the first answer is 3. Operation 66 then produces (2,1,3,4,5,6)(2,1,3,4,5,6), containing only the inversion (2,1)(2,1), so the second answer is 1.

Example 2

Input

3
3 2 1
2
2 3

Output

2
1

Explanation

Initially (3,2,1)(3,2,1) has three inversions. Operation 22 swaps the first pair, producing (2,3,1)(2,3,1) with two inversions. Operation 33 leaves (2,3)(2,3) unchanged and swaps (3,1)(3,1), producing (2,1,3)(2,1,3) with one inversion. The two answers are 2 and 1.