題目大意:給定一個長度爲n的正整數數列a[i]。
定義2個位置的graze值爲兩者位置差與數值差的和,即graze(x,y)=|x-y|+|a[x]-a[y]|。
2種操作(k都是正整數):
1.Modify x k:將第x個數的值修改爲k。
2.Query x k:詢問有幾個i滿足graze(x,i)<=k。因爲可持久化數據結構的流行,詢問不僅要考慮當前數列,還要考慮任意歷史版本,即統計任意位置上出現過的任意數值與當前的a[x]的graze值<=k的對數。(某位置多次修改爲同樣的數值,按多次統計)
雙倍經驗同BZOJ4170(樣例都一樣233)
這道題妙啊,所以不寫簡化題意了。
首先,可以講數列上的每一個元素看作是二維平面上的一個點(i,a[i]),記爲O(i)。那麼graze(x,y)即爲O(x)和O(y)在二維平面上的曼哈頓距離。
曼哈頓距離<=k,可以在平面上畫出一個菱形(斜的正方形),菱形不好查詢..於是將座標系旋轉45°,原座標(x,y)變爲(x-y,x+y),則變成查詢一個矩形內有多少點。我選擇主席樹。
因爲要查詢所有歷史版本,所以修改就等於加點。再給主席樹加一個樹狀數組,這道題就做完啦
#include <cstdio>
#include <algorithm>
#define N 300000
#define M 100000
using namespace std;
inline int lowbit(int x) { return x & -x; }
namespace Segment_Tree {
struct Node {
Node* ch[2];
int sum;
Node(Node* o=NULL) {
if(o==NULL) sum=0, ch[0]=ch[1]=NULL;
else sum=o->sum, ch[0]=o->ch[0], ch[1]=o->ch[1];
}
void* operator new(size_t) {
static Node *mempool,*C;
if(mempool==C) mempool=(C=new Node[1<<20])+(1<<20);
return C++;
}
}*root[N+5];
void Update(Node*& o,int l,int r,int pos,int delta) {
Node* tmp=o;
o=new Node(tmp);
o->sum+=delta;
if(l==r) return ;
int mid=l+r>>1;
if(pos<=mid) Update(o->ch[0],l,mid,pos,delta);
else Update(o->ch[1],mid+1,r,pos,delta);
return ;
}
int Query(Node* o,int l,int r,int L,int R) {
if(!o) return 0;
if(l==L && r==R) return o->sum;
int mid=L+R>>1;
if(r<=mid) return Query(o->ch[0],l,r,L,mid);
if(l>mid) return Query(o->ch[1],l,r,mid+1,R);
return Query(o->ch[0],l,mid,L,mid)+Query(o->ch[1],mid+1,r,mid+1,R);
}
}
#define ST Segment_Tree
struct Point {
int x,y;
Point() {}
Point(int _x,int _y):x(_x),y(_y) {}
Point rotated() {
int nx=x-y+M,ny=x+y+M;
if(nx<1) nx=1;
if(nx>N) nx=N;
if(ny<1) ny=1;
if(ny>N) ny=N;
return Point(nx,ny);
}
}p[N/3+5];
int main() {
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) {
int x;
scanf("%d",&x);
p[i]=Point(i,x);
Point tmp=p[i].rotated();
using ST::Update;
using ST::root;
for(int j=tmp.x;j<=N;j+=lowbit(j))
Update(root[j],1,N,tmp.y,1);
}
while(m--) {
char mode[10];
int x,y;
scanf("%s%d%d",mode,&x,&y);
if(mode[0]=='Q') {
Point a=Point(p[x].x-y,p[x].y),b=Point(p[x].x+y,p[x].y);
a=a.rotated(), b=b.rotated();
using ST::root; using ST::Query;
int ans=0;
for(int j=a.x-1;j;j-=lowbit(j)) ans-=Query(root[j],a.y,b.y,1,N);
for(int j=b.x;j;j-=lowbit(j)) ans+=Query(root[j],a.y,b.y,1,N);
printf("%d\n",ans);
}
else {
p[x].y=y;
Point tmp=p[x].rotated();
using ST::root; using ST::Update;
for(int j=tmp.x;j<=N;j+=lowbit(j))
Update(root[j],1,N,tmp.y,1);
}
}
return 0;
}