排序按最小, 最大, 次小, 次大, 依次排序。
比如 1 2 3 4 5 -> 1 5 2 4 3
代码如下:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define M 1000000007
#define LL long long
const int maxn = 1000007;
LL a[maxn] ,b[maxn];
LL min(LL a,LL b)
{
if( a < b) return a;
return b;
}
void exgcd(LL a, LL b, LL &x, LL &y)
{
if(b == 0)
{
x = 1;
y = 0;
return;
}
exgcd(b, a%b, x, y);
LL t = x; x = y; y = t - a / b * y;
}
int main()
{
int t, n;
scanf("%d", &t);
while(t --)
{
scanf("%d", &n);
LL ans = 1, ans1;
for(int i = 0; i < n; i ++)
{
scanf("%I64d", &a[i]);
ans = ans * a[i] % M;
}
ans1 = ans * n % M;
sort(a, a + n);
int t = 0;
for(int i = 0;i <= n/2; i ++)
{
b[t++] = a[i];
b[t++] = a[n - 1 - i];
}
LL sum = 0;
for(int i = 0; i < n - 1; i ++)
{
LL x, y;
LL mi = min(b[i], b[i + 1]);
LL temp = b[i] * b[i + 1];
exgcd(temp, M, x, y);
while(x < 0) x += M;
LL ret = ( ans * x )% M;
sum = (sum + ret * mi % M) % M; //如果改成sum +=(ret * mi % M)% M; 就Wrong掉了
}
ans = ( ans1 + M - sum ) % M;
printf("%I64d\n",ans);
}
return 0;
}
注意:第 63 行, 居然在这wrong掉了……不过后来想想也对,如果改成后一种写法的话,得到的sum值有可能会超过 M ,,,