//KDtree
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e7+10;
const int NIL=-1;
struct node{
int location,l,r;
};
struct point{
int id,x,y;
friend bool operator <(const point &a,const point &b){
return a.id<b.id;
}
};
void print(point a)
{
printf("%d\n",a.id);
}
int n,np;
point p[maxn];
node t[maxn];
bool lessx(const point p1,const point p2){return p1.x<p2.x;}
bool lessy(const point p1,const point p2){return p1.y<p2.y;}
//建造KDtree
int makekdtree(int l,int r,int depth)
{
if(!(l<r)){
return NIL;
}
int mid=(l+r)>>1;
int T=np++;
if(depth%2==0){
sort(p+l,p+r,lessx);
}else{
sort(p+l,p+r,lessy);
}
t[T].location=mid;
t[T].l=makekdtree(l,mid,depth+1);
t[T].r=makekdtree(mid+1,r,depth+1);
return T;
}
void find(int v,int sx,int tx,int sy,int ty,int depth,vector<point>&ans)
{
int x=p[t[v].location].x;
int y=p[t[v].location].y;
if(sx<=x&&x<=tx&&sy<=y&&y<=ty){
ans.push_back(p[t[v].location]);
}
if(depth%2==0){
if(t[v].l!=NIL){
if(sx<=x){
find(t[v].l,sx,tx,sy,ty,depth+1,ans);
}
}
if(t[v].r!=NIL){
if(x<=tx){
find(t[v].r,sx,tx,sy,ty,depth+1,ans);
}
}
}else{
if(t[v].l!=NIL){
if(sy<=y){
find(t[v].l,sx,tx,sy,ty,depth+1,ans);
}
}
if(t[v].r!=NIL){
if(y<=ty){
find(t[v].r,sx,tx,sy,ty,depth+1,ans);
}
}
}
}
int main()
{
int x,y;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d%d",&x,&y);
p[i].id=i;
p[i].x=x;
p[i].y=y;
t[i].l=t[i].r=NIL;
}
np=0;
int root=makekdtree(0,n,0);
int q;
scanf("%d",&q);
int sx,tx,sy,ty;
vector<point>ans;
for(int i=0;i<q;i++){
scanf("%d%d%d%d",&sx,&tx,&sy,&ty);
ans.clear();
find(root,sx,tx,sy,ty,0,ans);
sort(ans.begin(),ans.end());
for(int j=0;j<ans.size();j++){
print(ans[j]);
}
printf("\n");
}
return 0;
}
KD 树
最新推荐文章于 2024-02-19 11:22:31 发布