cdq
作者:
Lemmon_kk
,
2020-07-10 16:07:05
,
所有人可见
,
阅读 506
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define N 1000005
using namespace std;
typedef long long LL;
int n;
int a[N];
int ans[N];
struct Node{
int op, a, b, id;
}q[N], tmp[N];
bool cmpa(const Node& n1, const Node& n2){
if(n1.a == n2.a) return n1.op < n2.op;
else return n1.a < n2.a;
}
bool cmpb(const Node& n1, const Node& n2){
if(n1.b == n2.b) return n1.op > n2.op;
else return n1.b > n2.b;
}
void solve(int l, int r){
if(l == r) return ;
int mid = l + r >> 1;
solve(l, mid);
sort(q + l, q + r + 1, cmpb);
// merge(q + l, q + mid + 1, q + mid + 1, q + 1 + r, q0 + l, cmpb);//O(len)
// for(int i = l;i <= r;i ++ ){//O(len)
// q[i] = q0[i];
// }
int cnt = 0;
for(int i = l;i <= r;i ++ ){//O(len)
if(q[i].op == 1 && q[i].a <= mid) ++ cnt;
if(q[i].op == 2 && q[i].a >= mid+1) ans[q[i].id] += cnt;
}
for(int i = l;i <= r;i ++ ){//O(len)
q[i] = tmp[i];
}
solve(mid + 1, r);
}
int main(){
// ios::sync_with_stdio(0);
cin >> n;
for(int i = 1;i <= n;i ++ ){
cin >> a[i];
// insert
q[i].a = i;
q[i].b = a[i];
q[i].op = 1;
// query
q[i + n].a = i;
q[i + n].b = a[i];
q[i + n].op = 2;
q[i + n].id = i;
}
// 按 a 排序 给每个数分配唯一的时间轴
sort(q + 1, q + 1 + 2 * n, cmpa);
for(int i = 1;i <= 2 * n;i ++ )
q[i].a = i;
memcpy(tmp, q, sizeof q);
solve(1, 2 * n);
LL res = 0;
for(int i = 1;i <= n;i ++ ){
res += ans[i];
}
cout << res << endl;
return 0;
}