原题链接:http://ac.jobdu.com/problem.php?pid=1521
水题,如下。。
1 #include<algorithm> 2 #include<iostream> 3 #include<cstdlib> 4 #include<cstring> 5 #include<cstdio> 6 #include<vector> 7 using std::cin; 8 using std::swap; 9 using std::vector; 10 const int Max_N = 1010; 11 struct Node { 12 int v, rev; 13 Node *fa, *ch[2]; 14 inline void set(int _v, Node *p) { 15 v = _v, rev = 0; 16 fa = ch[0] = ch[1] = p; 17 } 18 inline void link(Node *x, bool d) { 19 ch[d] = x; 20 x->fa = this; 21 } 22 inline void update() { 23 rev ^= 1; 24 swap(ch[0], ch[1]); 25 } 26 inline void push_down() { 27 if (rev != 0) { 28 ch[0]->update(); 29 ch[1]->update(); 30 rev ^= 1; 31 } 32 } 33 }; 34 struct BinaryTree { 35 Node *root, *null, *tail, *ptr[Max_N], stack[Max_N]; 36 void init() { 37 tail = &stack[0]; 38 null = tail++; 39 null->set(0, NULL); 40 root = null; 41 } 42 inline Node *newNode(int v) { 43 Node *p = tail++; 44 p->set(v, null); 45 return p; 46 } 47 inline void gogo(int n) { 48 char c; 49 int i, v, a, b; 50 for (i = 1; i <= n; i++) { 51 scanf("%d", &v); 52 ptr[i] = newNode(v); 53 } 54 for (i = 1; i <= n; i++) { 55 cin >> c; 56 if (c == 'd'){ 57 scanf("%d %d", &a, &b); 58 ptr[i]->link(ptr[a], 0); 59 ptr[i]->link(ptr[b], 1); 60 } else if (c == 'l') { 61 scanf("%d", &a); 62 ptr[i]->link(ptr[a], 0); 63 } else if (c == 'r') { 64 scanf("%d", &b); 65 ptr[i]->link(ptr[b], 1); 66 } 67 if (ptr[i]->fa == null) root = ptr[i]; 68 } 69 } 70 inline void PreOder(Node *x, vector<int> &res) { 71 if (x != null) { 72 x->push_down(); 73 res.push_back(x->v); 74 PreOder(x->ch[0], res); 75 PreOder(x->ch[1], res); 76 } 77 } 78 inline void PreOder() { 79 vector<int> res; 80 if (root == null) { 81 puts("NULL"); 82 return; 83 } 84 root->update(); 85 PreOder(root, res); 86 int n = res.size(); 87 for (int i = 0; i < n; i++) { 88 printf("%d%c", res[i], i < n - 1 ? ' ' : ' '); 89 } 90 } 91 }tree; 92 int main() { 93 #ifdef LOCAL 94 freopen("in.txt", "r", stdin); 95 freopen("out.txt", "w+", stdout); 96 #endif 97 int n; 98 while (~scanf("%d", &n)) { 99 tree.init(); 100 tree.gogo(n); 101 tree.PreOder(); 102 } 103 return 0; 104 }