AcWing 1215. 小朋友排队
原题链接
中等
作者:
Value
,
2020-10-16 09:23:22
,
所有人可见
,
阅读 427
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1E5 + 10, M = N * 10;
int tr[M], h[N];
int sum[N];
int lowbit(int x){
return x & -x;
}
void add(int index, int a){
for(int i = index; i < M; i += lowbit(i)) tr[i] += a;
}
int query(int x){
int sum = 0;
for(int i = x; i ; i -= lowbit(i)) sum += tr[i];
return sum;
}
int main(){
int n; cin >> n;
for(int i = 1; i <= n; i ++ ){
cin >> h[i];
h[i] ++ ;
}
for(int i = 1; i <= n; i ++ ){
sum[i] += query(M - 1) - query(h[i]);
add(h[i], 1);
}
memset(tr, 0, sizeof tr);
for(int i = n; i ; i -- ){
sum[i] += query(h[i] - 1);
add(h[i], 1);
}
typedef long long ll;
ll res = 0;
for(int i = 1; i <= n; i ++ ) res += ((ll)sum[i] * (sum[i] + 1) / 2);
cout << res << endl;
return 0;
}