Problem description
Given n nn integers a 1, a 2,..., a n a_{1}, a_{2}, \cdots, a_{n}a1,a2,⋯,an
Find the sum of them multiplied by two and then added together, that is
S = a 1 ⋅ a 2 + a 1 ⋅ a 3 + ⋯ + a 1 ⋅ a n + a 2 ⋅ a 3 + ⋯ + a n − 2 ⋅ a n − 1 + a n − 2 ⋅ a n + a n − 1 ⋅ a n S=a_{1} \cdot a_{2}+a_{1} \cdot a_{3}+\cdots+a_{1} \cdot a_{n}+a_{2} \cdot a_{3}+\cdots+a_{n-2} \cdot a_{n-1}+a_{n-2} \cdot a_{n}+a_{n-1} \cdot a_{n}
S=a1⋅a2+a1⋅a3+⋯+a1⋅an+a2⋅a3+⋯+an−2⋅an−1+an−2⋅an+an−1⋅an
Input format
The first line of input contains an integer n nn.
The second line contains n nn integers a 1, a 2,... a n a_{1}, a_{2}, \cdots a_{n}a1,a2
,⋯an.
Output format
Outputs an integer S SS representing the desired sum. Please use the appropriate data type for the calculation.
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N = 100010, mod = 1000000009;
int a[N];
int main()
{
int n, k;
cin >> n >> k;
for (int i = 0;i < n;i++) scanf("%d", &a[i]);
sort(a, a + n);
LL res = 1;
int l = 0, r = n - 1;
int sign = 1;
if (k % 2)
{
res = a[r];
r--;
k--;
if (res < 0) sign = -1;
}
while (k)
{
LL x = (LL)a[l] * a[l + 1], y = (LL)a[r] * a[r - 1];
if (x * sign > y * sign)
{
res = x % mod * res % mod;
l += 2;
}
else
{
res = x % mod * res % mod;
res -= 2;
}
k -= 2;
}
cout << res << endl;
return 0;
}