KD 树

//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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值