AcWing 1215. 小朋友排队
原题链接
中等
作者:
wjie
,
2020-07-01 12:59:53
,
所有人可见
,
阅读 583
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5 + 5;
int tree[N], h[N], tmp[N], maxSize;
long long swapCnt[N];
int lowbit(int x)
{
return x & (-x);
}
void updateTree(int x, int c)
{
for (int i = x; i <= maxSize; i += lowbit(i))
tree[i] += c;
}
int queryTree(int x)
{
int res = 0;
for (int i = x; i > 0; i -= lowbit(i))
res += tree[i];
return res;
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
{
scanf("%d", &h[i]);
tmp[i] = h[i];
}
//离散化
sort(tmp+1, tmp+1+n);
maxSize = unique(tmp+1, tmp+1+n) - (tmp+1);
for (int i = 1; i <= n; ++i)
h[i] = lower_bound(tmp+1, tmp+1+maxSize, h[i])-(tmp+1)+1;
// for (int i = 1; i <= n; ++i)
// printf("%d ", h[i]);
for (int i = 1; i <= n; ++i)
{
swapCnt[i] = queryTree(maxSize) - queryTree(h[i]);
// cout << swapCnt[i] << endl;
updateTree(h[i], 1);
}
memset(tree, 0, sizeof(tree));
for (int i = n; i >= 1; --i)
{
swapCnt[i] += queryTree(h[i] - 1);
updateTree(h[i], 1);
}
long long res = 0;
for (int i = 1; i <= n; ++i)
{
res += (1 + swapCnt[i]) * swapCnt[i] / 2;
}
printf("%lld", res);
return 0;
}