题意:已知n个建筑的坐标(x,y)和高度,查询点(x,y)的左下角中高度第k小的建筑的高度。
解题思路:坐标加高度相当于是一个三维的题目。首先要发现这里的k非常小,所以我们只要用线段树维护区间内最小的10个建筑的高度。现将查询与建筑一起离散化处理,采用巧妙的降维方式,将x、y、flag(是否为建筑)的优先级排序,y作为线段树下标。对于建筑只要进行单点更新操作即可,查询操作是一个区间[1,pos]的查询。
代码如下:
#include<iostream> #include<cstdio> #include<algorithm> #define N 30005 using namespace std; struct node { int x,y,k,flag,id; bool operator < (const node &rhs)const { if(x != rhs.x) return x < rhs.x; if(y != rhs.y) return y < rhs.y; return flag < rhs.flag; } }s[N*2]; int a[N*2]; struct tree { int l,r,sum; int num[23]; }tree[N*8]; void build(int o,int l,int r) { tree[o].l = l; tree[o].r = r; tree[o].sum = 0; if(l == r) return; int m = (l+r)/2; build(2*o,l,m); build(2*o+1,m+1,r); } void del(int o)//只记录一个区间的10个最小值 { sort(tree[o].num,tree[o].num+tree[o].sum); if(tree[o].sum > 10) tree[o].sum = 10; } void pushup(int o) { int i; int k = 0; for(i = 0; i < tree[2*o].sum; i++) tree[o].num[k++] = tree[2*o].num[i]; for(i = 0; i < tree[2*o+1].sum; i++) tree[o].num[k++] = tree[2*o+1].num[i]; tree[o].sum = k; del(o); } void update(int o,int pos,int k) { if(tree[o].l == tree[o].r) { tree[o].num[tree[o].sum++] = k; del(o); return; } int m = (tree[o].l+tree[o].r)/2; if(pos <= m) update(2*o,pos,k); else update(2*o+1,pos,k); pushup(o); } int path[25],sz; void query(int o,int x,int y) { if(x <= tree[o].l && tree[o].r <= y) { for(int i = 0; i < tree[o].sum; i++) path[sz++] = tree[o].num[i]; sort(path,path+sz); if(sz > 10) sz = 10; return; } int m = (tree[o].l + tree[o].r)/2; if(x <= m) query(2*o,x,y); if(y > m) query(2*o+1,x,y); } int ans[N*2]; int main() { int n,m; while(scanf("%d%d",&n,&m) != EOF) { int i,tot = 0; for(i = 0; i < n+m; i++) { scanf("%d%d%d",&s[i].x,&s[i].y,&s[i].k); if(i < n) s[i].flag = 0; else s[i].flag = 1; s[i].id = i; a[tot++] = s[i].y; } sort(s,s+n+m); sort(a,a+tot);//将y坐标离散话处理 tot = unique(a,a+tot) - a; build(1,1,tot); for(i = 0; i < n+m; i++) { int pos = lower_bound(a,a+tot,s[i].y) - a + 1; if(s[i].flag == 0) { update(1,pos,s[i].k); } else { sz = 0; query(1,1,pos); if(sz < s[i].k) ans[ s[i].id ] = -1; else ans[ s[i].id ] = path[ s[i].k-1 ]; } } for(i = n; i < n+m; i++) { printf("%d\n",ans[i]); } } return 0; } /* 5 3 1 1 2 2 2 3 2 4 4 3 1 6 4 4 1 2 3 2 1 1 1 4 4 1 */
讯享网

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/110100.html