一道逆序数的题。要用两个树状数组来维护,一个记录牛的数目,另一个记录牛的脾气值.一定要注意数据溢出.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
typedef long long LL;
#define maxn 100005
int c[maxn], n;
LL num[maxn];
void Update(LL m){
int h = m;
while(m <= n){
num[m] += h;
c[m] += 1;
m += m & -m;
}
}
int Query(int m, LL &p){
int sum = 0;
while(m){
p += num[m];
sum += c[m];
m -= m & -m;
}
return sum;
}
int main(){
// freopen("in.txt", "r", stdin);
while(cin >> n){
memset(c, 0, sizeof(c));
memset(num, 0, sizeof(num));
LL s = 0, sum = 0;
for(int i = 1; i <= n; i++){
LL a, p = 0;
cin >> a;
s += a;
Update(a);
sum += (i - Query(a, p))*a + s - p;
}
cout << sum << endl;
}
return 0;
}