# 问题 1439: [蓝桥杯][历届试题]小朋友排队

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

typedef long long ll;
const int maxn = 100005;
const int maxm = 1000005;
int n,h[maxn],cnt[maxm],sum[maxm];
int lowbit(int x) {
return x&(-x);
}
void deal() {
memset(sum,0,sizeof(sum));
memset(cnt,0,sizeof(cnt));
for(int i = 0; i < n; i++) {
//h[i] ~ maxm 都大于等于h[i]。
for(int k = h[i]; k < maxm; k=k+lowbit(k)) {
cnt[k] += 1;
}
int j = 0;
for(int k = h[i]; k > 0; k=k-lowbit(k)) {
j += cnt[k];
}
sum[i] = i-j+1;  //算元素i左侧有多少大于等于元素i的。
}
memset(cnt,0,sizeof(cnt));
for(int i = n-1; i >= 0; i--) {
for(int k = h[i]; k < maxm; k=k+lowbit(k)) {
cnt[k] += 1;
}
for(int k = h[i]-1; k > 0; k=k-lowbit(k)) {
sum[i] += cnt[k];
}
}
}
int main() {
scanf("%d",&n);
for(int i = 0; i < n; i++) {
scanf("%d",&h[i]);
h[i]++;
//h[i]可能是0，导致lowbit(0) 一直是0，所以用树状数组一定要注意这点。
}
deal();
ll ans = 0;
for(int i = 0; i < n; i++) {
ans += ((ll)sum[i]+1)*(ll)sum[i]/2;
}
printf("%lld\n",ans);
return 0;
}

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

typedef long long ll;
const int maxn = 100005;
int arr[maxn],cnt1[maxn],tmp[maxn],cnt2[maxn];
void mergePass(int L1,int R1,int L2,int R2) {
int i,j,k;
i = L1;    //i指向左区间左端点
j = L2;    //j指向右区间右端点
k = 0;
while(i<=R1 && j<=R2) {
if(arr[i]>arr[j]) {
cnt2[k] = cnt1[j] + (R1-i+1);
tmp[k++] = arr[j++];
}
else {
cnt2[k] = cnt1[i] + (j-L2);
tmp[k++] = arr[i++];
}
}
while(i<=R1) {
cnt2[k] = cnt1[i] + (R2-L2+1);
tmp[k++] = arr[i++];
}
while(j<=R2) {
cnt2[k] = cnt1[j];
tmp[k++] = arr[j++];
}
for(int i = L1; i <= R2; i++) {
arr[i] = tmp[i-L1];
cnt1[i] = cnt2[i-L1];
}
}
void mergeSort(int left,int right) {
if(left<right) {
int mid = (left+right)/2;
mergeSort(left,mid);
mergeSort(mid+1,right);
mergePass(left,mid,mid+1,right);
}
}
int main() {
int n;
while(~scanf("%d",&n)) {
for(int i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
memset(cnt1,0,sizeof(cnt1));
memset(cnt2,0,sizeof(cnt2));
mergeSort(0,n-1);
ll ans = 0;
for(int i = 0; i < n; i++) {
ans += ((ll)cnt1[i]+1)*(ll)cnt1[i]/2;
}
printf("%lld\n",ans);
}
return 0;
}