ABSP1 - abs(a-b) I

no tags 

Recently Mr. Kopa Samsu is learning programming. On a very renowned online judge, he found a problem:

You are given an array of N numbers in non-decreasing order. You have to answer the summation of the absolute difference of all distinct pairs in the given array.

Do you know what distinct pair means? Suppose you have an array of 3 elements: 3 5 6

Then all the distinct pairs are:

3 5
3 6
5 6

For this problem, Mr. Kopa Samsu implemented an algorithm to find the summation of the absolute difference of all distinct pairs. His algorithm was:

int ABS(int a[], int n)
{
    int sum = 0;
    for (int i = 1; i <= n ;i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            sum += abs(a[i] - a[j]);
        }
    }
}

After a great hard work, he finished the code. But alas!!! Frustration came around him when he submitted his code, the judge gave the verdict “TLE” (Time Limit Exceeded). “How can I get rid of TLE?” he thought a lot but couldn't find any way. Then suddenly, he remembered about you that you (his friend) is very good at programming. So, he came to you seeking your help. Can you help him solving this problem?

Input

The input data set starts with an integer T (T ≤ 1000), the number of test cases. Then every test case starts with a integer N (N ≤ 10000), the number of elements in the array. After that, the next line contains N integers A[i], where 1 ≤ i ≤ N and 1 ≤ A[i] ≤ 1000000000 and A[i] ≤ A[i+1].

Output

Every test case should output an integer “X”, where X is the summation of the absolute difference of all the distinct pair.

Example

Input:
3
3
1 2 3
3
1 4 5
3
2 4 6

Output:
4
8
8

Problem Set: S.M. Shaheen Sha, Raihat Zaman Neloy

Data Set & Solution: Raihat Zamane Neloy


hide comments
nonushikhar: 2016-06-26 22:52:01

distinct pair means index wise distinct not numerically

sanjay: 2016-05-29 12:34:31

Simple math.Thanks to the author.:)

vinu0103: 2016-04-03 03:24:37

can array contain a single element

dokz: 2016-01-27 09:24:19

Easy AC in 0.40 C# with O(n) algorithm.

minhthai: 2016-01-11 06:39:13

the problem statement is so misleading that it made me wanna cry :((

Mohit Rathore: 2016-01-10 12:32:09

An array of N numbers in *non-decreasing order*.

dwij28: 2015-12-27 17:13:18

Nice problem .. AC in one go.. Problems like these become easier to solve once you take a pen and paper .. :)

Prashanth: 2015-11-20 19:38:58

Got AC after changing long int to long long int.

Pulkit Mittal: 2015-10-17 09:50:07

problem incorrectly stated @Raihat Zaman Neloy

Last edit: 2015-10-17 09:51:06
quirk: 2015-09-28 15:53:46

Apparently the problem statement is misleading. So for the list: {1,2,2,4,4} the pairs considered are
(1,2) -> (twice)
(1,4) -> (twice)
(2,4) -> (four times)
The correct answer being 16.

Last edit: 2015-09-28 15:54:15

Added by:Raihat Zaman Neloy
Date:2014-01-25
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64