- #include <iostream>
- #include <algorithm>
- using namespace std;
- struct treap
- {
- int key, pri, cnt;
- treap *lc, *rc;
- treap(int x, int y);
- }NIL=treap(0,0), *nil=&NIL;
- treap::treap(int x=0, int y=0)
- {
- key=x,pri=y,cnt=1;
- lc=rc=nil;
- }
- typedef treap*node;
- node root;
- void right_rotate(node &y)
- {
- node x = y->lc;
- y->lc = x->rc;
- x->rc = y;
- y = x;
- }
- void left_rotate(node &x)
- {
- node y = x->rc;
- x->rc = y->lc;
- y->lc = x;
- x = y;
- }
- void insert(node &t, int x)
- {
- if(t == nil)
- {
- t = new treap(x,rand()*rand());
- }
- else if(x == t->key) t->cnt++;
- else if(x < t->key)
- {
- insert(t->lc, x);
- if(t->lc->pri < t->pri) right_rotate(t);
- }
- else if(x > t->key)
- {
- insert(t->rc, x);
- if(t->rc->pri < t->pri) left_rotate(t);
- }
- }
- void del(node &t, int x)
- {
- if(t == nil)return;
- if(x < t->key) del(t->lc, x);
- else if(x > t->key) del(t->rc, x);
- else
- {
- if(t->cnt > 1) {t->cnt--;return;}
- else if(t->lc==nil) t = t->rc;
- else if(t->rc==nil) t = t->lc;
- else
- {
- if(t->lc->pri < t->rc->pri)
- {
- right_rotate(t);
- del(t->rc,x);
- }
- else
- {
- left_rotate(t);
- del(t->lc,x);
- }
- }
- }
- }
- int succ(node t, int x)
- {
- if(t==nil)return -1;
- if(x > t->key) return succ(t->rc, x);
- else if(x == t->key) return x;
- else
- {
- int tmp=succ(t->lc, x);
- if(tmp==-1)return t->key;
- else return tmp;
- }
- }
- int main()
- {
- int i, j, k, t;
- int n, q, y;
- scanf("%d", &t);
- for(k = 1; k <= t; k++)
- {
- scanf("%d%d%d", &n, &q, &y);
- root = nil;
- for(i = 0; i < n; i++)
- {
- scanf("%d", &j);
- insert(root, j);
- }
- printf("Case %d:/n", k);
- for(i = 0; i < q; i++)
- {
- scanf("%d", &j);
- int tmp = succ(root, j);
- if(tmp == -1 || tmp-j>y) puts("-1");
- else
- {
- del(root, tmp);
- printf("%d/n", tmp);
- }
- }
- }
- }