标签:
The most interesting, flexible and juicy binary tree problem I have ever seen.
I learnt it from here: https://codepair.hackerrank.com/paper/5fIoGg74?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6IkJsdWVCaXJkMjI0IiwiZW1haWwiOiJoZWFsdGh5dG9ueUBnbWFpbC5jb20ifQ%3D%3D
Everything is so generalized.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; struct node { long value, size; int prev; node *left, *right; }; const long MAX_N = 100000l; node nodes[MAX_N]; long values[MAX_N]; // Get Tree Size long size(node *p) { return p ? p->size : 0; } // Tree Operations // node *merge(node *l, node *r) { if (!l) return r; if (!r) return l; if (l->prev > r->prev) { l->right = merge(l->right, r); l->size = size(l->left) + size(l->right) + 1; return l; } // l is on left of r: append l to r‘s left r->left = merge(l, r->left); r->size = size(r->left) + size(r->right) + 1; return r; } // split tree p by inx, to l and r void split(node *p, long inx, node *&l, node *&r) { if (!p) { l = r = nullptr; return; } long cur = size(p->left) + 1; if (cur <= inx) { split(p->right, inx - cur, p->right, r); l = p; } else { split(p->left, inx, l, p->left); r = p; } p->size = size(p->left) + size(p->right) + 1; } // node *extract(node *&p, long from, long to) { node *l, *m, *r; split(p, from, l, m); split(m, to - from, m, r); p = merge(l, r); return m; } // Traversal long preorder(node *p, long i/*from inx*/) // return new start inx { if (!p) return i; i = preorder(p->left, i); values[i++] = p->value; return preorder(p->right, i); } int main() { for (long i = 0; i != MAX_N; ++i) { nodes[i].prev = rand(); nodes[i].size = 1; } long n, m; cin >> n >> m; node *tree = nullptr; for (long i = 0; i != n; ++i) { cin >> nodes[i].value; tree = merge(tree, nodes + i); } for (long i = 0; i != m; ++i) { long l, r; int type; cin >> type >> l >> r; node *sub = extract(tree, l - 1, r); if (type == 1) tree = merge(sub, tree); else tree = merge(tree, sub); } // Serialize tree preorder(tree, 0); cout << abs(values[0] - values[n-1]) << endl; for (long i = 0; i < n; ++i) cout << values[i] << " "; cout << endl; return 0; }
HackerRank "Array and simple queries" !
标签:
原文地址:http://www.cnblogs.com/tonix/p/4985614.html