1. 程式人生 > >HDU 4585 Shaolin 找最接近的數 Treap / set

HDU 4585 Shaolin 找最接近的數 Treap / set

題目連結

題意

若干組插入與詢問,每次詢問與當前要插入的數最接近的數。

思路

向左走向右走的時候記錄一下即可。

(是最近寫的 Treap 裡面最簡單的了(躺倒

寫部落格的時候想了一下,為啥不用 set 呢!因為是搜 HDU 上 Treap 相關的題目搜到的這題...。
用 set 幾行就搞定了嗎= =而且寫 Treap 就相當於自己寫了個 set 啊…。
(寫 set 一開始一直 t,後來才知道 lower_bounds.lower_bound(x) 而不是 lower_bound(s.begin(), s.end(), x)

Code

Treap

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f using namespace std; map<int, int> m; struct node { node* ch[2]; int val, key, sz; node() { sz = 0; key = INT_MAX; } node(int x); void update() { sz = ch[0]->sz + ch[1]->sz + 1; } }* null = new node; node::node(int x) { sz = 1, val = x, key = rand(); ch[0
] = ch[1] = null; } struct Treap { node* root; Treap() { root = null; } bool empty() { return root == null; } void rotate(node*& t, bool d) { node* p = t->ch[d]; t->ch[d] = p->ch[!d]; p->ch[!d] = t; t->update(), p->update(); t = p; } void
insert(node*& t, int x, int& lo, int& hi) { if (t == null) { t = new node(x); return; } bool d = x > t->val; if (d == 0) hi = t->val; else lo = t->val; insert(t->ch[d], x, lo, hi); if (t->ch[d]->key < t->key) rotate(t, d); else t->update(); } int findpos(int x) { int lo = -inf, hi = inf; insert(root, x, lo, hi); return hi-x < x-lo ? hi : lo; } void clear(node*& t) { if (t->ch[0] != null) clear(t->ch[0]); if (t->ch[1] != null) clear(t->ch[1]); delete t; t = null; } void clear() { clear(root); } void insert(int x) { int lo, hi; insert(root, x, lo, hi); } }* treap = new Treap; int n, id, x; void work() { if (!treap->empty()) treap->clear(); treap->insert(1000000000); m.clear(); m[1000000000] = 1; for (int i = 0; i < n; ++i) { scanf("%d%d", &id, &x); m[x] = id; printf("%d %d\n", id, m[treap->findpos(x)]); } } int main() { while (scanf("%d", &n) && n) work(); return 0; }

Set

#include <bits/stdc++.h>
using namespace std;
map<int, int> m;
set<int> s;
int n, id, x;
void work() {
    s.clear(); s.insert(1000000000);
    m.clear(); m[1000000000] = 1;
    for (int i = 0; i < n; ++i) {
        scanf("%d%d", &id, &x);
        auto it = s.lower_bound(x);
        int g;
        if (it == s.begin()) g = *it;
        else if (it == s.end()) g = *(--it);
        else {
            int hi = *it; int lo = *(--it);
            g = hi - x < x - lo ? hi : lo;
        }
        printf("%d %d\n", id, m[g]);
        m[x] = id;
        s.insert(x);
    }
}
int main() {
    while (scanf("%d", &n) != EOF && n) work();
    return 0;
}