BZOJ 2683: 简单题 [CDQ分治]

时间:2022-06-21 22:14:08

同上题

那你为什么又发一个?

因为我用另一种写法又写了一遍...

不用排序,$CDQ$分治的时候归并排序

快了1000ms...

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
const int N=1e6+;
inline int read(){
char c=getchar();int x=,f=;
while(c<''||c>''){if(c=='-')f=-;c=getchar();}
while(c>=''&&c<=''){x=x*+c-'';c=getchar();}
return x*f;
}
int n,op,m;
struct Operation{
int x,y,v,id;
int qid,op;
Operation():op(){}
Operation(int x,int y,int v,int id,int qid,int op):
x(x),y(y),v(v),id(id),qid(qid),op(op){}
bool operator <(const Operation &r)const{
return x==r.x?op<r.op:x<r.x;
}
}a[N],t[N];
int ans[N],qid;
void devideQuery(){
int x1=read()-,y1=read()-,x2=read(),y2=read();
qid++;
m++;a[m]=Operation(x2,y2,,m,qid,);
m++;a[m]=Operation(x1,y2,-,m,qid,);
m++;a[m]=Operation(x2,y1,-,m,qid,);
m++;a[m]=Operation(x1,y1,,m,qid,);
}
int c[N];
inline int lowbit(int x){return x&-x;}
inline void add(int p,int v){for(;p<=n;p+=lowbit(p)) c[p]+=v;}
inline int sum(int p){
int re=;
for(;p;p-=lowbit(p)) re+=c[p];
return re;
}
void CDQ(int l,int r){
if(l==r) return;
int mid=(l+r)>>;
CDQ(l,mid);CDQ(mid+,r);
int i=l,j=mid+,p=l;
while(i<=mid||j<=r){
if(j>r||(i<=mid&&a[i]<a[j])){
if(!a[i].op) add(a[i].y,a[i].v);
t[p++]=a[i++];
}else{
if(a[j].op) ans[a[j].qid]+=a[j].v*sum(a[j].y);
t[p++]=a[j++];
}
}
for(int i=l;i<=r;i++) if(a[i].id<=mid&&!a[i].op) add(a[i].y,-a[i].v);
for(int i=l;i<=r;i++) a[i]=t[i];
}
int main(){
freopen("in","r",stdin);
n=read();
m=;
while(true){
op=read();
if(op==) a[++m].x=read(),a[m].y=read(),a[m].v=read(),a[m].id=m;
else if(op==) devideQuery();
else break;
}
CDQ(,m);
for(int i=;i<=qid;i++) printf("%d\n",ans[i]);
}