This problem is actually a binary search tree inside to find the precursor and follow-up, as if with a line of tree + discretization has been done, make a relatively setback, learned AVL is convenient after.
Simply say how to find the precursor and the successor,
If the current node has a left dial hand tree, then the precursor is the largest node in the left Dial hand tree, or the first one is the node of the right son of his father's node, the successor is similar to the predecessor, and vice versa.
Because I do not have the parent pointer here, if it is more troublesome to rotate, so I first find this node from the root, along the way recorded a bit.
#include <cstdio> #include <climits> #include <cstring> #include <cmath> #include <algorithm > #include <string> #include <vector> #include <map> #include <set> #include <list># Include <queue> #include <stack>using namespace std;typedef long long ll;const int MAXN = 2e5 + 10;struct Node {Node *ch[2];int Rkey, Val, size, id; Node (int val, int id): Val (val), id (ID) {ch[0] = ch[1] = Null;rkey = rand (); size = 1;} void maintain () {size = 1;if (ch[1]! = null) size + = Ch[1]->size;if (ch[0]! = null) size + = ch[0]->size;}}; void Rotate (node *&o, int D) {node *k = o->ch[d ^ 1];o->ch[d ^ 1] = K->ch[d];k->ch[d] = O;o->maintain () ; K->maintain (); o = k;} void Insert (Node *&o, int x, int id) {if (o = = NULL) o = new Node (x, id); else {int d = x > O->val;insert (o->ch [d], X, id), if (O->ch[d]->rkey > O->rkey) rotate (o, D ^ 1);} O->maintain ();} void Remove_tree (Node *&o) {if (o = = NULL) return;if>CH[0]! = null) Remove_tree (o->ch[0]), if (o->ch[1]! = null) Remove_tree (o->ch[1]);d elete (o); o = NULL;} node* query (Node *o, int x, int dx) {//dx = 0Node *pre = Null;while (o! = NULL && O->val! = x) {int d = x > O ->val;if (d = = dx ^ 1) Pre = O;o = O->ch[d];} o = o->ch[dx];if (o = = null) return Pre;else {while (o->ch[dx ^ 1]! = NULL) o = o->ch[dx ^ 1];return o;}} int Calc (Node *r, int k) {if (R = = NULL) return Int_max;return abs (R->VAL-K);} Node *root;int N;int Main () {while (scanf ("%d", &n), n! = 0) {remove_tree (root); Insert (root, 1e9, 1); for (int i = 1; I & lt;= N; i++) {int id, k, ans; scanf ("%d%d", &id, &k); Insert (root, k, id); Node *r0 = Query (root, k, 0), *r1 = query (root, K, 1), int d0 = Calc (r0, k), D1 = Calc (r1, k); if (D0 > D1) ans = r1->i D;else ans = r0->id;printf ("%d%d\n", id, ans);}} return 0;}
HDU 4585 Shaolin Foundation Treap