题解:P10633 BZOJ2989 数列/BZOJ4170 极光
这是一道可癌的三维偏序题。
前置知识
- 曼哈顿距离与切比雪夫距离的相互转化
- 【模板】三维偏序(陌上花开)
- [BalkanOI 2007] Mokia 摩基亚
思路
把曼哈顿距离转换为切比雪夫距离,就是把
这样问题就变为了时间轴、
Code
#include<bits/stdc++.h>
using namespace std;
const int N = 3e5 + 5,M = 3e5 + 5,MAXN = 3e5 + 5;
struct node{
int ti,x,y,w;
} e[N],t[N];
int n,Q,a[M],cnt,ti,ans[N],tmp[N],m;
string opt;
vector<int> pos;
namespace Bit{
int cnt[MAXN];
void add(int x,int v){
for(;x <= m;x += x & -x){
cnt[x] += v;
}
}
int query(int x){
int res = 0;
for(;x > 0;x -= x & -x){
res += cnt[x];
}
return res;
}
}
void cdq(int l,int r){
if(l == r){
return;
}
int mid = (l + r) >> 1;
cdq(l,mid);
cdq(mid + 1,r);
int p = l,q = mid + 1,cnt = 0;
while(p <= mid and q <= r){
if(e[p].x <= e[q].x){
if(e[p].w == 0){
Bit::add(e[p].y,1);
}
t[++cnt] = e[p ++];
}else{
if(e[q].w != 0){
ans[e[q].ti] += Bit::query(e[q].y) * e[q].w;
}
t[++cnt] = e[q ++];
}
}
while(p <= mid){
if(e[p].w == 0){
Bit::add(e[p].y,1);
}
t[++cnt] = e[p ++];
}
while(q <= r){
if(e[q].w != 0){
ans[e[q].ti] += Bit::query(e[q].y) * e[q].w;
}
t[++cnt] = e[q ++];
}
for(int i = l;i <= mid;i ++){
if(e[i].w == 0){
Bit::add(e[i].y,-1);
}
}
for(int i = l;i <= r;i ++){
e[i] = t[i - l + 1];
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> Q;
for(int i = 1;i <= n;i ++){
cin >> a[i];
e[++cnt] = {0,i + a[i],i - a[i],0};
}
while(Q --){
cin >> opt;
if(opt == "Modify"){
int x,y;
cin >> x >> y;
e[++cnt] = {++ti,x + y,x - y,0};
tmp[cnt] = x - y;
a[x] = y;
}else{
int x,y,k;
cin >> x >> k;
y = x - a[x];
x = a[x] + x;
e[++cnt] = {++ti,x + k,y + k,1};
tmp[cnt] = y + k;
e[++cnt] = {ti,x + k,y - k - 1,-1};
tmp[cnt] = y - k - 1;
e[++cnt] = {ti,x - k - 1,y + k,-1};
tmp[cnt] = y + k;
e[++cnt] = {ti,x - k - 1,y - k - 1,1};
tmp[cnt] = y - k - 1;
pos.push_back(ti);
}
}
sort(tmp + 1,tmp + cnt + 1);
m = unique(tmp + 1,tmp + cnt + 1) - tmp - 1;
for(int i = 1;i <= cnt;i ++){
e[i].y = lower_bound(tmp + 1,tmp + m + 1,e[i].y) - tmp;
}
cdq(1,cnt);
for(int i : pos){
cout << ans[i] << '\n';
}
return 0;
}