Sum of differences

The sum of
differences The
idea of sum of differences : Obviously n^2 violent enumeration will definitely time out, because they ask us to find the sum of absolute values, so we can sort these numbers first, find the prefix sum, and then directly + the current value* (Ni) Subtract the sum of the following numbers (it is better to use the prefix sum to calculate).
Code

#include<bits/stdc++.h>
using namespace std;
long long n,i,j,a[1000000],as[1000000],s;
bool cmp(int a,int b){
    
    
	return a>b;
}
int main(){
    
    
	scanf("%lld",&n);
	for(i=1;i<=n;i++)scanf("%lld",&a[i]);
	sort(a+1,a+1+n,cmp);
	for(i=1;i<=n;i++)as[i]+=as[i-1]+a[i];
	for(i=1;i<=n;i++)
		s+=abs(a[i]*(n-i)-(as[n]-as[i]));
	printf("%lld",s);
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_52536621/article/details/113443805
sum
Recommended