目录
1.Problem
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.
There are nn positive integers a1,a2,…,ana1,a2,…,an on Bob's homework paper, where nn is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 22 numbers. Suppose the numbers are divided into mm groups, and the sum of the numbers in the jj-th group is sjsj. Bob's aim is to minimize the sum of the square of sjsj, that is
∑j=1ms2j.∑j=1msj2.
Bob is puzzled by this hard problem. Could you please help him solve it?
2.Input
The first line contains an even integer nn (2≤n≤3⋅1052≤n≤3⋅105), denoting that there are nn integers on Bob's homework paper.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1041≤ai≤104), describing the numbers you need to deal with.
3.Output
A single line containing one integer, denoting the minimum of the sum of the square of sjsj, which is
∑i=jms2j,∑i=jmsj2,
where mm is the number of groups.
4.Examples
4.1input
4
8 5 2 3
4.2output
164
5.Code
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int readInt() {
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9') {
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int main() {
int n = readInt();
ll a[300005];
for(int i = 1; i <= n; i++) {
a[i] = readInt();
}
sort(a + 1, a + n + 1);
ll ans = 0;
for(int i = 1; i <= n / 2; i++) {
ll sum = a[i] + a[n - i + 1];
ans += sum * sum;
}
cout << ans << endl;
return 0;
}
6.Conclusion
这段C++代码的主要功能是对输入的整数数组进行排序,然后计算数组中每对元素之和的平方,将所有平方和相加并输出。以下是代码的大致功能介绍:
通过
readInt
函数读取一个整数n
,表示数组的大小。声明一个名为
a
的数组,存储n
个long long
类型的整数。使用循环读取
n
个整数,将其存储在数组a
中。对数组
a
进行升序排序。使用循环,从数组的两端同时取元素,计算每对元素之和,然后将这个和的平方累加到
ans
变量中。输出最终的累加结果
ans
。总体而言,这段代码的作用是对输入的整数数组进行排序,然后计算数组中每对元素之和的平方,将所有平方和相加,并输出最终的结果。这样的操作通常在数学和计算中用于分析数据的分布或计算某种关联度。