Hide

Problem Z
Continuous Median

In Statistics, the median of an array A of N integers is a value which divides array A into two equal parts: the higher half and the lower half.

In the case when N is odd, the median is clearly defined: the middle value of the sorted version of array A. In the case when N is even, the median is the average of the two middle values, rounded down so that we always have an integer median.

In this problem, your task is to compute median values as integers are added into array A one by one. Since this is an incremental process, we call these “continuous medians”. To simplify this problem, you just need to output the sum of the medians of A at the end.

Input

The first line of input contains an integer T, denoting the number of test cases (1T100). Each test case consists of two lines and the first line contains just one integer N (1N105). This is followed by N integers of array A in the next line. Each integer in A is non-negative and is not more than 109.

Note: For all input, there will be at most 400000 integers.

Output

For each test case, output the sum of the continuous medians of A in one line.

Explanation

In the first sample test case, N=6 and A={1,3,6,2,7,8}. When you read the ith integer of array A, you need to compute the current continuous median of array A=[A0,A1,,Ai], as shown in Table 1. Thus, 1+2+3+2+3+4=15 is the answer for this first sample test case.

iAiASorted-AContinuous Median01[1][1]113[1,3][1,3](1+3)/2=226[1,3,6][1,3,6]332[1,3,6,2][1,2,3,6](2+3)/2=247[1,3,6,2,7][1,2,3,6,7]358[1,3,6,2,7,8][1,2,3,6,7,8](3+6)/2=4
Table 1: Explanation of Sample Test Case 1. The sum of the continuous medians is 1+2+3+2+3+4=15.

Subtasks

  1. (10 points): 1T20, 1N500

  2. (10 points): 1T100, 1N500

  3. (40 points): 1T100, 1N3000

  4. (40 points): 1T4, 1N100000

Sample Input 1 Sample Output 1
2
6
1 3 6 2 7 8
7
1 3 6 2 7 8 5
15
20
Hide

Please log in to submit a solution to this problem

Log in