题意: 直接看样例:
Consider 6 possible routes:
- [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5;
- [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7;
- [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7;
- [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8;
- [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9;
- [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8.
The average travel distance is =
=
.
The first line contains integer n (2 ≤ n ≤ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 107).
题解:
ai出现的次数是 (n-1)!,|ai-aj|出现的次数是(n-1)*2 (假设a[]数组已经排过序,即 ai>aj)
观察: 数组 2 3 5 6
6-2= 6-5 + 5-3 + 3-2
5-2= 5-3 + 3-2
3-2= 3-2
6-3= 6-5 + 5-3
5-3= 5-3
6-5= 6-5
d[]数组 表示前后两个a[]数组的差。
上代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll __int64
using namespace std;
ll a[100005],d[100005];
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
int main()
{
int i,n,m;
ll sum;
while(~scanf("%d",&n))
{
sum=0;
for(i=0;i<n;i++)
{
scanf("%I64d",&a[i]);
sum+=a[i];
}
sort(a,a+n);
m=n-1;
for(i=1;i<=m;i++)
d[i]=a[i]-a[i-1];
for(i=1;i<=m;i++)
sum+=d[i]*i*(n-i)*2; // 如果 数组是int类型, 这些乘积的结果可能会越界!!
ll t=gcd(sum,n);
printf("%I64d %I64d\n",sum/t,n/t);
}
return 0;
}