CDQ分治 学习笔记
我们先回顾一下逆序对问题:
在本题中,我们需要求所有
想一下我们是怎么求解的:我们一个一个地把
但如果我们需要求关于
题意:设
我们运用刚才的思想,我们首先以
我们考虑归并:对于一个区间
- 当
时,我们把 在树状数组中加上 (显然地,一个对数合法了,相同的也一定合法),并增加 ; - 当
时,我们对 加上树状数组中小于 的前缀和。由于对 进行排序,所以此时加上的一定是合法的数量。
排序完后,我们需要再将原本的树状数组每个
对整个区间归并后,每个
不清楚的可以看代码理解。
AC Code:
#include <bits/stdc++.h>
#define lowbit(x) ((x) & -(x))
#define mid (l + r >> 1)
using namespace std;
struct P {
int a, b, c, id, cnt;
const bool operator<(const P &rhs) const {
if (a != rhs.a)
return a < rhs.a;
else if (b != rhs.b)
return b < rhs.b;
else
return c < rhs.c;
}
const bool operator==(const P &rhs) const {
return a == rhs.a && b == rhs.b && c == rhs.c;
}
};
int n, k, tot, ans[100005], f[100005], sum[200005];
P p[100005];
map<P, int> ma;
void add(int id, int d) {
while (id <= k) {
sum[id] += d;
id += lowbit(id);
}
}
int query(int id) {
int res = 0;
while (id) {
res += sum[id];
id -= lowbit(id);
}
return res;
}
void mergeSort(int l, int r) {
if (l == r)
return;
mergeSort(l, mid), mergeSort(mid + 1, r);
int lptr = l, rptr = mid + 1, t = 0;
P *tmp = new P[r - l + 2];
while (lptr <= mid && rptr <= r)
if (p[lptr].b > p[rptr].b) {
tmp[++t] = p[rptr];
ans[p[rptr].id] += query(p[rptr].c);
++rptr;
} else {
tmp[++t] = p[lptr];
add(p[lptr].c, p[lptr].cnt);
++lptr;
}
while (lptr <= mid) {
tmp[++t] = p[lptr];
add(p[lptr].c, p[lptr].cnt);
++lptr;
}
while (rptr <= r) {
tmp[++t] = p[rptr];
ans[p[rptr].id] += query(p[rptr].c);
++rptr;
}
for (int i = l; i <= mid; ++i)
add(p[i].c, -p[i].cnt);
for (int i = l; i <= r; ++i)
p[i] = tmp[i - l + 1];
delete tmp;
}
int main() {
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; ++i) {
++tot;
scanf("%d %d %d", &p[tot].a, &p[tot].b, &p[tot].c);
if (ma[p[tot]]) {
++p[ma[p[tot]]].cnt;
--tot;
} else {
ma[p[tot]] = tot;
p[tot].cnt = 1;
p[tot].id = tot;
}
}
sort(p + 1, p + tot + 1);
mergeSort(1, tot);
for (int i = 1; i <= tot; ++i)
f[ans[p[i].id] + p[i].cnt - 1] += p[i].cnt;
for (int i = 0; i < n; ++i)
printf("%d\n", f[i]);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】