思路:
维护两个前缀和,然后直接求
c o d e code code
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long n;
long long a[100100], b[100100], sumb[100100], sumb_[100100];
int main()
{
// freopen("D:\\菜鸡咕\\mat6.in", "r", stdin);
scanf("%lld", &n);
for(long long i=1; i<=n; i++)
scanf("%lld", &a[i]);
for(long long i=1; i<=n; i++)
scanf("%lld", &b[i]);
sort(b+1, b+1+n);
for(long long i=1; i<=n; i++)
sumb[i]=sumb[i-1]+b[i], sumb_[i]=sumb_[i-1]+b[i]*b[i];
double ans=0;
for(long long i=1; i<=n; i++)
{
if(a[i]<=b[1]){ans-=(n*a[i]*a[i]-2ll*a[i]*sumb[n]+sumb_[n]); continue;}
if(a[i]>=b[n]){ans+=n*a[i]*a[i]-2ll*a[i]*sumb[n]+sumb_[n]; continue;}
long long l=1, r=n, w=0;
while(l<=r)
{
long long mid=l+r>>1;
if(a[i]>=b[mid])
l=mid+1, w=mid;
else
r=mid-1;
}
ans+=-((n-w)*a[i]*a[i]-2ll*a[i]*(sumb[n]-sumb[w])+sumb_[n]-sumb_[w])+w*a[i]*a[i]-2ll*a[i]*sumb[w]+sumb_[w];
}
printf("%.1lf", ans/(n*1.0));
return 0;
}