hdu5107(線段樹處理三維問題)

很不錯的一道線段樹題,這裏的降維方式值得我們學習。
題意:已知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


*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章