coderforces round 19D线段树+离散化处理

点击打开链接

题意:共有三种操作,add:向平面中加入一个点x,y,remove:将平面中的一个点删除,find x,y查询平面内严格大于x,y的点,要求这个点横坐标越小越好,然后再保证纵坐标越小越好,不存在这样的点输出-1。

思路:因为x,y的范围很大,所以先将x坐标的值离散化,然后以x的位置和对应y的值保存到set中,线段树节点保存区间最大值,查询时也查询大于x的位置,然后二分求得y的位置即可。下面有注释。

#include <set>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=200010;
set<int>s[maxn];
set<int>:: iterator ite;
int num[maxn*4],x[maxn],y[maxn],t[maxn];
char str[maxn][20];
void pushup(int node){
    num[node]=max(num[node<<1],num[node<<1|1]);
    //节点保存y轴的最大值
}
void update(int pos,int yy,int op,int le,int ri,int node){
    //pos为离散后x的值,yy为x对应的y轴坐标
    if(le==ri){
        //op只为1添加,值为0删除
        if(op){
            num[node]=max(num[node],yy);
            s[le].insert(yy);
        }else{
            s[le].erase(yy);
            num[node]=*(s[le].end());//因为可能一个x对应了多个y,保证最大值,所以将num[node]的值改为x现在对应的最大值
        }
        return ;
    }
    int t=(le+ri)>>1;
    if(pos<=t) update(pos,yy,op,le,t,node<<1);
    else update(pos,yy,op,t+1,ri,node<<1|1);
    pushup(node);
}
int query(int l,int r,int yy,int le,int ri,int node){
    if(num[node]<=yy) return -1;
    if(l<=le&&ri<=r){
        if(le==ri) return le;
        int t=(le+ri)>>1;
        if(num[node<<1]>yy) return query(l,r,yy,le,t,node<<1);
        //这应该不用讲了,找最小的点大于查询的点,所以尽可能的先满足左侧的点
        //只要num[node<<1]大于yy,说明左儿子区间内有大于yy的点,并且满足尽量小的条件
        if(num[node<<1|1]>yy) return query(l,r,yy,t+1,ri,node<<1|1);
        return -1;
    }
    int t=(le+ri)>>1;
    if(l<=t){
        int k=query(l,r,yy,le,t,node<<1);
        if(k!=-1) return k;
    }
    if(r>t){
        int k=query(l,r,yy,t+1,ri,node<<1|1);
        if(k!=-1) return k;
    }
    return -1;
}
int main(){
    int n;
    while(scanf("%d",&n)!=-1){
        for(int i=0;i<maxn;i++) s[i].clear();
        memset(num,0,sizeof(num));
        int k=0;
        for(int i=0;i<n;i++){
            scanf("%s%d%d",str[i],&x[i],&y[i]);
            t[k++]=x[i];
        }
        sort(t,t+k);
        int len=unique(t,t+k)-t;
        //将x坐标进行离散化,毕竟10的9次方
        for(int i=0;i<n;i++){
            int pos=lower_bound(t,t+len,x[i])-t+1;
            //当前x的位置
            if(str[i][0]=='a') update(pos,y[i],1,1,len,1);
            else if(str[i][0]=='r') update(pos,y[i],0,1,len,1);
            else{
                int ans=query(pos+1,len,y[i],1,len,1);
                //pos+1因为题目要求严格大于询问的坐标,所以从下一个开始查询
                if(ans==-1) printf("-1\n");
                else printf("%d %d\n",t[ans-1],*(s[ans].upper_bound(y[i])));
                //找到了x的坐标,但因为t数组从0开始,结果减去1,y坐标用二分进行快速查询
            }
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值