按照每个人的pow值来从小到大排序,对于每次计算只需要计算比当前的pow小的部分,计算完之后加入树状数组。
开两个树状数组分别记录数量和总距离,对于每个计算而言,每次求出当前点左边和右边的总距离 与 当前点的权值 的乘积累加 就可以了。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 20000+20;
typedef long long LL;
LL lowbit(LL x)
{return x & (-x);}
struct Person
{
LL pos , val;
}p[maxn];
LL n ;
struct TREE_ARRAY
{
LL c[maxn];
void add(LL x, LL d)
{
while(x <= maxn)
{
c[x] += d;
x += lowbit(x);
}
}
LL sum1(LL x)
{
LL ret = 0;
while(x > 0)
{
ret += c[x];
x -= lowbit(x);
}
return ret;
}
LL sum2(LL from , LL to)
{
return sum1(to-1) - sum1(from-1);
}
}cnt , sum;
bool cmp (const Person &t1,const Person &t2)
{
return t1.val < t2.val;
}
int main()
{
cin >> n;
for(int i = 0 ;i < n ;i++)
{
cin >> p[i].val >> p[i].pos;
}
sort(p,p+n,cmp);
LL cnt1 = 0 ;
for(int i=0;i<n;i++)
{
LL left = cnt.sum2(1,p[i].pos) , right = cnt.sum2(p[i].pos , maxn);
cnt1 += ( left * p[i].pos - sum.sum2(1,p[i].pos) + sum.sum2(p[i].pos ,maxn) - right * p[i].pos ) * p[i].val;
cnt.add(p[i].pos,1);
sum.add(p[i].pos,p[i].pos);
}
cout << cnt1 << endl;
return 0;
}