1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <iostream> #include <string> struct node{ node *p, *ch[2]; std::string s; int col; int flag() {return p->ch[1] == this;} node(node *, std::string, int); } *root, *null; node::node(node *p, std::string s, int c) : p(p), s(s), col(c) {ch[0] = ch[1] = null;} void Rotate(node *y) { node *x = y->p; int f = !y->flag(); if (x == root) (root = y)->p = null; else (x->p->ch[x->flag()] = y)->p = x->p; (x->ch[!f] = y->ch[f])->p = x; (y->ch[f] = x)->p = y; } void FixUp(node *x) { for (; !x->p->col; x = x->p->p) { int f = x->p->flag(); if (!x->p->p->ch[!f]->col) { x->p->col ^= 1; x->p->p->col ^= 1; x->p->p->ch[!f]->col ^= 1; } else { if (x->flag() != f) Rotate(x); else x = x->p; x->col ^= 1; x->p->col ^= 1; Rotate(x); break; } } root->col = 1; } void Insert(node *&x, node *p, std::string s) { if (x == null) FixUp(x = new node(p, s, 0)); else Insert(x->ch[s >= x->s], x, s); } void Inorder(node *x) { std::cout << x->s << (x->col ? ":black" : ":red") << std::endl; if (x->ch[0] != null) Inorder(x->ch[0]); if (x->ch[1] != null) Inorder(x->ch[1]); } int Find(node *x, std::string s) { if (s == x->s || x == null) return 0; return Find(x->ch[s >= x->s], s) + 1; } int main() { root = null = new node(0, std::string(""), 1); null->p = null->ch[0] = null->ch[1] = null; int n, m; std::cin >> n >> m; for (std::string s; n; --n) std::cin >> s, Insert(root, null, s); Inorder(root); for (std::string s; m; --m) std::cin >> s, std::cout << Find(root, s) << std::endl; }
|