排序二叉树 HDOJ 5444 Elven Postman
题意:给出线性排列的树,第一个数字是根节点,后面的数如果当前点小或相等往左走,否则往右走,查询一些点走的路径
分析:题意略晦涩,其实就是排序二叉树!1<<1000 普通数组开不下,用指针省内存。将树倒过来好理解些
E---------------------------------------W 2 / \ 1 4 / 3 6 / 5 / 4 / 3 / 2 / 1 E---------------------------------------W
收获:排序二叉树插入和查询
代码:
/************************************************ * Author :Running_Time * Created Time :2015/9/14 星期一 15:34:35 * File Name :H.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int N = 1e3 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; int a[N], q[N]; struct BST { int val; BST *left, *right; BST *insert(BST *p, int x) { if (p == NULL) { BST *t = new BST; t->val = x; t->left = t->right = NULL; return t; } if (x <= p->val) p->left = insert (p->left, x); else p->right = insert (p->right, x); return p; } bool find(BST *p, int x) { if (x == p->val) return true; else if (p == NULL) return false; else if (x <= p->val) { cout << "E"; return find (p->left, x); } else { cout << "W"; return find (p->right, x); } } }bst; int main(void) { ios::sync_with_stdio (false); int T; cin >> T; while (T--) { int n; cin >> n; for (int i=1; i<=n; ++i) { cin >> a[i]; } int m; cin >> m; for (int i=1; i<=m; ++i) { cin >> q[i]; } BST *root = NULL; for (int i=1; i<=n; ++i) { root = bst.insert (root, a[i]); } for (int i=1; i<=m; ++i) { bst.find (root, q[i]); cout << endl; } } return 0; }
编译人生,运行世界!