题目传送门
COGS 2580. [HZOI 2015]偏序 II
Solution
由于周围的神犇们都学了CDQ分治,菜鸡我整天对他们的讨论一头雾水,于是我也照葫芦画瓢地学了一发,然后就找了一道CDQ分治裸题,来自我愉悦一下。
首先CDQ分治和整体二分有些相像,我个人的理解就是CDQ分治是注重过程的二分,整体二分则是直接二分答案,然后将操作划分。
CDQ一般的套路就是将一段可看成修改和询问操的作序列按时间排好序,去掉时间限制,然后划分为二成
[L,mid],[mid+1,R]
,先处理左边,然后通过排序,数据结构处理左边的修改对右边询问的贡献,然后处理右边(有时如果不用先算左边的话,先处理中间也可以)。
对于n维偏序问题,编号已有序,层层CDQ下去,按不同的关键字排序,最后一层用跟求逆序对(即二维偏序)一样的方法,存进一个权值BIT中修改和查询。
三维坐标最长不降子序列和矩形动态区间和问题也可以用类似的手段解决。
不过这都基于一个大前提:题目支持离线操作。强制在线不能排序的话就只能树套树了。
言归正传,这题就是求五维偏序,明显离线,直接用CDQ套几下CDQ。
首先第一维的编号已经排好序了,都是左边影响右边了。处理左边,然后一起按
a
排序,搞下一层,然后处理右边。按这样继续处理下一层(基于a排
b
,然后排c),每一层的的左边的修改相对于右边的询问都绝对满足前面的所有关键字顺序(这里的“修改”和“查询”是上一轮打上标记了的,我们将偏序对的统计,理解成修改和查询的关系)。
到第三层,处理左边对右边的影响就直接用BIT去做,BIT以第五维关键字做下标,是修改操作就Add,查询就Sum。做完记得像整体二分一样反向标记,清空BIT。
然后此果题就是这样做了,时间复杂度是
O(nlog4n)。
以上是一个初接触CDQ分治的蒟蒻的口胡,请各位神犇轻喷。。
Code
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#define MAXN 50005
using namespace std;
int n, BIT[MAXN], ans, turn;
struct Data{
int id, a, b, c, d;
bool type;
}op[
5][MAXN];
bool cmp(Data A, Data B){
if(turn ==
1)
return A.a < B.a;
if(turn ==
2)
return A.b < B.b;
return A.c < B.c;
}
int lowbit(
int x){
return x & (-x);
}
void Add(
int x,
int v){
for(
int i = x; i <= n; i += lowbit(i)) BIT[i] += v;
}
int Sum(
int x){
int res =
0;
for(
int i = x; i >
0; i -= lowbit(i)) res += BIT[i];
return res;
}
int Work(
int cnt){
int res =
0;
for(
int i =
1; i <= cnt; i++){
if(!op[
3][i].type) Add(op[
3][i].d,
1);
else res += Sum(op[
3][i].d);
}
for(
int i =
1; i <= cnt; i++)
if(!op[
3][i].type) Add(op[
3][i].d, -
1);
return res;
}
void CDQ(
int now,
int L,
int R){
if(L == R)
return;
int mid = (L + R) >>
1, cnt =
0;
CDQ(now, L, mid);
for(
int i = L; i <= mid; i++){
if(now ==
1) op[now][++cnt] = op[now-
1][i], op[now][cnt].type =
false;
else if(!op[now-
1][i].type) op[now][++cnt] = op[now-
1][i];
}
for(
int i = mid+
1; i <= R; i++){
if(now ==
1) op[now][++cnt] = op[now-
1][i], op[now][cnt].type =
true;
else if(op[now-
1][i].type) op[now][++cnt] = op[now-
1][i];
}
if(cnt){
turn = now;
sort(op[now]+
1, op[now]+cnt+
1, cmp);
if(now ==
3) ans += Work(cnt);
else CDQ(now+
1,
1, cnt);
}
CDQ(now, mid+
1, R);
}
int main(){
freopen(
"partial_order_two.in",
"r", stdin);
freopen(
"partial_order_two.out",
"w", stdout);
scanf(
"%d", &n);
for(
int i =
1; i <= n; i++)
scanf(
"%d", &op[
0][i].a);
for(
int i =
1; i <= n; i++)
scanf(
"%d", &op[
0][i].b);
for(
int i =
1; i <= n; i++)
scanf(
"%d", &op[
0][i].c);
for(
int i =
1; i <= n; i++)
scanf(
"%d", &op[
0][i].d);
for(
int i =
1; i <= n; i++) op[
0][i].id = i;
CDQ(
1,
1, n);
printf(
"%d\n", ans);
return 0;
}
最美丽的谎言,将你带到了我的身边。