POJ2352(Treap || 線段樹)

題目鏈接:http://poj.org/problem?id=2352
題目大意:先按Y的升序然後再按X的升序給出座標,求出每個座標左下方有多少個點,最後輸出有從0到n-1個點的座標有多少個。
本題可以說是線段樹和樹狀數組的入門題,不用管Y按順序依次求出每個X插入之前0到x有多少個座標即可。這道題還可以用Treap來做,也是模板題,由於是剛學Treap,就用這個來寫了。

資料:樹堆,在數據結構中也稱Treap,是指有一個隨機附加域滿足堆的性質的二叉搜索樹,其結構相當於以隨機數據插入的二叉搜索樹。其基本操作的期望時間複雜度爲O(logn)。相對於其他的平衡二叉搜索樹,Treap的特點是實現簡單,且能基本實現隨機平衡的結構。
右旋

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <ctime>
#include <cstdlib>

using namespace std;

const int maxn = 20000 + 5;
int cnt = 1, rt = 0;//第一個節點從1開始
int n, ans[maxn], x, y;
struct Tree{
    int key, pri, size, son[2];
    //插入值,優先級,大小,左右兒子
    void set(int x, int y, int z)//初始化
    {
        key = x;
        pri = y;
        size = z;
        son[0] = son[1] = 0;
    }
}T[maxn];
void push_up(int rt)
{
    T[rt].size = T[T[rt].son[0]].size + 1 + T[T[rt].son[1]].size;
}
void rotate(int p, int &x)//旋轉時左旋右旋放在一起
{                       //p=1時左旋,p=0時右旋
    int y = T[x].son[!p];
    T[x].son[!p] = T[y].son[p];
    T[y].son[p] = x;
    push_up(x), push_up(y);
    x = y;
}

void Insert(int key, int &x)
{//每次插入時從根遍歷插到葉子節點,然後再回溯旋轉
    if (x == 0)
    {
        T[x=cnt++].set(key, rand(), 1);
        return;
    }
    else {
        T[x].size++;
        int p = key <= T[x].key;
        Insert(key, T[x].son[!p]);
        if (T[x].pri > T[T[x].son[!p]].pri)
            rotate(p, x);
    }
}

int find(int key, int &x)
{
    if (x == 0) return 0;
    if (key >= T[x].key)
        return T[T[x].son[0]].size + 1 + find(key, T[x].son[1]);
    else return find(key, T[x].son[0]);
}
int main()
{
    //freopen("input.txt", "r", stdin);
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        scanf("%d%d", &x, &y);
        ans[find(x, rt)]++;
        Insert(x, rt);
    }
    for (int i = 0; i < n; i++) printf("%d\n", ans[i]);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章