c语言/c++编程题 之 Absolute Value

本文介绍如何计算数组中每对数字的绝对值。God Wang提出了一个解决此类问题的公式,通过这个公式可以高效地处理数组元素间的绝对值计算。博客内容将深入探讨这一数学问题在C语言和C++编程中的应用。

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

题目描述

God Wang, who may good at math, want to make a research on the absolute value. As a god, he want to build something hard to show his great intelligence.
One day, he meets an array with n integers.

In order to connect the array with his research, he wants to calculate the absolute value of each pair numbers of the array{ ai  }. As God Wang is so smart that he work out the formula of this problem:

God Wang finds out a way to solve it with an algorithm with time complexity of O(n^2), that is enumerate each pair numbers of the array.
God Wang believes that this is the best way to solve the problem. So, you can work out this problem with a faster algorithm if you are smarter than God Wang.
Now, it’s time to show your greater intelligence.

输入

There will be several cases.
The first line of the input gives the number of test cases, T ( T=10 ). T test cases follow.
Each test cases begins with a single integer n( 1≤n≤2*10^5  ), the size of the array.
The second line contains n integers a_i (| ai |≤ 10^9  ) to describe the array.
There are at most 3 test cases with n > 10^3

输出

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the answer mod 1000000007.

样例输入

2
3
1 2 3
4
10 1000 1 100

样例输出

Case #1: 4
Case #2: 3087

题意:给你n个数a1,a2,a3....an;计算

分析:先排序,再后面的减去前面的,演绎推理,找规律

AC代码如下:

#include<bits/stdc++.h>


using namespace std;


const int MOD = 1000000007;
int t , n;
long long a[2000000];


int main()
{
	scanf( "%d" , &t );
	for( int ca = 1 ; ca <= t ; ca++ )
	{
		scanf( "%d" , &n );
		for( int i = 0 ; i < n ; i++ )
			scanf( "%lld" , &a[i] );
		sort( a , a+n );
		long long ans = 0;
		for( int i = 0 ; i < n ; i++ )
			ans = (ans+(2*i+1-n)*a[i])%MOD;//精华所在,读者自己体会
		printf( "Case #%d: %lld\n" , ca , (ans+MOD)%MOD );
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值