2014新生暑假个人排位赛09---470. diffsum

时间限制 1000 ms  内存限制 65536 KB

题目描述

You are givin an array of integers, and you are to figure out the sum of differences between each pair of integers belonging to the array. SEE THE HINT FOR MORE INFORMATION.

输入格式

There are multiple test cases. The first line contains an integer n(n<=1e5), size of the array. The second line contains n integers, ai(|ai|<=100000), the array.

输出格式

For each case, output one line, the answer.

输入样例

4
1 1 2 2

输出样例

4

hint
for the test case the answer is abs(1-1)+abs(1-2)+abs(1-2)+abs(1-2)+abs(1-2)+abs(2-2)=4.
这道题不断地wa。结果还是因为int爆了,这样的问题已经被坑过很多次了,还是没有记住教训!然后是为了不超时不能暴力,这里又要用到数学规律了,多列几个式子,然后就是要考虑正负数以及绝对值,还要注意n=1的情况。
code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
long long a[100006];
int main()
{         long long  n;
         while (~ scanf ( "%lld" ,&n))
         {
             long long sum=0;
             if (n==1)
             {
                 scanf ( "%lld" ,&a[0]);
                 a[0]= abs (a[0]);
                 printf ( "%lld\n" ,a[0]);
             }
             else
             {
                 for ( int i=0;i<n;i++)
                     scanf ( "%lld" ,&a[i]);
                 sort(a,a+n);
                 for ( int i=0;i<n;i++)
                     sum=sum+(a[i]*(n-1-i)-a[i]*i);
                 sum= abs (sum);
                 printf ( "%lld\n" ,sum);
             }
         }
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值