Paired Up
Problem Statement
You are given a list of n integers X=[x1, x2, ..., xn]. Now, imagine you have a list P of all pairings of integers from 1 to n such that P is sorted in increasing order. In other words, you have:
\begin{array}{rcc} P &=& \Big[\ \normalsize(1, 1), (1, 2), (1, 3), ..., (1, n),\ & & \ \ \ (2, 1), (2, 2), (2, 3), ..., (2, n), \ & & \ ...\ & & \ \ \ \ \ \ (n, 1), (n, 2), (n, 3), ..., (n, n)\ \Big]\normalsize \ \end{array}
Now, you are given Q queries, each will contain a single integer qi such that 1≤qi≤∣P∣, given some qi you should determine f(qi):
\begin{array}{rcl} f(k) &=& \sum_{i=1}^{k} x_{P_i[0]} - x_{P_i[1]} \end{array}
In other words, f(k) takes the first k pairs in P, and for each pair (a,b) it will calculate xa−xb and sum all of them together.
Input Format
Your first line will contain two space-separated integers n and q
Your next line will contain n space-separated integers x1 through xn.
Your next Q lines will contain one integer each, the ith of which representing qi.
Output Format
You should output a single integer for each query (in the same order the queries appear), the ith of which should be f(qi).
Constraints
- 1≤n,q≤105
- 1≤qi≤n2
- −103≤xi≤103
Sample Cases
3 3
11 7 5
4
6
9
6
8
0
Explanation 1
Here P=[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)].
For the first query q1=4, we calculate (x1−x1)+(x1−x2)+(x1−x3)+(x2−x1)=(11−11)+(11−7)+(11−5)+(7−11)=6. For the second query q1=6, we calculate (x1−x1)+(x1−x2)+(x1−x3)+(x2−x1)+(x2−x2)+(x2−x3). For the third query q1=9, we calculate (x1−x1)+(x1−x2)+(x1−x3)+(x2−x1)+(x2−x2)+(x2−x3)+(x3−x1)+(x3−x2)+(x3−x3).
10 5
-5 10 -1 9 -4 6 3 -1 -7 -5
20
36
8
79
38
40
64
-57
126
80
Template
n, q = map(int, input().split())
numbers = list(map(int, input().split()))
queries = [int(input()) for _ in range(q)]
# print your output
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.