Wednesday, 1 July 2015

ABSP1

Standard

Abs(a-b) I

Link to the question: ABSP1 

HINT :

You must have already noticed that the number are in sorted order. If you do some rough work for input of 5-6 numbers and form pairs as given in the question and subtract you will notice that each element in the i-th position is added i-th times and subtracted n-1-i th times. Using this you can write your code.

SOURCE CODE :

/* ABSP1 */ /* Sushant Gupta */
#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,i;
        scanf("%d",&n);
        long long int a[n],s=0;
        for(i=0;i<n;i++)
            scanf("%lld",&a[i]);
        for(i=n-1;i>=0;i--)
            s= s+ (i*a[i]) - a[i]*(n-1-i);
        printf("%lld\n",s);
    }
    return 0;
}

0 comments:

Post a Comment