暑期个人赛--第九场--A

本篇介绍了一道算法题的解决方法,题目要求计算数组中所有整数对之间的差值绝对值之和。文章提供了一种高效算法,避免了n²的时间复杂度,通过一次排序和迭代计算达到了nlogn的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间限制 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.

赛中提交:RE AC


题目大意:

给出一组数,要求求出任意两者间差的绝对值之和。


思路:

一看到题目首先就觉得不能直接用n^2的朴素计算方法直接计算。

想了下,可以先用nlogn的sort先排序

然后求出后n-1个数对于a[0]的差之和sigema

接着求出a1-a0,再用sigema减去(n-1)*(a1-a0)就可以得到后n-2个数对于a1的差之和

下同



下面是ac代码:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <functional>
#define maxn 100005
 
using namespace std;
long long a[maxn];
long long b[maxn];
 
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF){
        for(int i=0;i<n;i+=1){
            scanf("%lld",&a[i]);
        }
        sort(a,a+n);
        long long sum=0,tmp;
        for(int i=0;i<n;i+=1){
            sum+=(a[i]-a[0]);
            //printf("%I64d\n",b[i]);
        }
        tmp=sum;
        for(int i=1;i<n;i+=1){
            b[i]=(a[i]-a[i-1])*(n-i);
            tmp=tmp-b[i];
            sum+=tmp;
        }
        printf("%lld\n",sum);
    }
 
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值