原题链接:http://ac.jobdu.com/problem.php?pid=1523
建树,再层次遍历bfs。为了找根方便些,加了father指针。。。
如下:
1 #include<algorithm> 2 #include<iostream> 3 #include<cstdlib> 4 #include<cstring> 5 #include<cstdio> 6 #include<vector> 7 #include<queue> 8 using std::queue; 9 using std::vector; 10 using std::cin; 11 const int Max_N = 1100; 12 struct Node{ 13 int v; 14 Node *f, *ch[2]; 15 inline void set(int _v = 0, Node *p = NULL){ 16 v = _v, f = ch[0] = ch[1] = p; 17 } 18 inline void link(Node *x, bool d){ 19 ch[d] = x; 20 x->f = this; 21 } 22 }; 23 struct BinaryTree{ 24 Node *tail, *root, *null; 25 Node stack[Max_N], *ptr[Max_N]; 26 void init(){ 27 tail = &stack[0]; 28 null = tail++; 29 null->set(); 30 root = null; 31 } 32 inline Node *newNode(int v){ 33 Node *p = tail++; 34 p->set(v, null); 35 return p; 36 } 37 inline void gogo(int n){ 38 char c; 39 int i, v, a, b; 40 for (i = 1; i <= n; i++){ 41 scanf("%d", &v); 42 ptr[i] = newNode(v); 43 } 44 for (i = 1; i <= n; i++){ 45 cin >> c; 46 if (c == 'd'){ 47 scanf("%d %d", &a, &b); 48 ptr[i]->link(ptr[a], 0); 49 ptr[i]->link(ptr[b], 1); 50 } else if (c == 'l'){ 51 scanf("%d", &a); 52 ptr[i]->link(ptr[a], 0); 53 } else if (c == 'r'){ 54 scanf("%d", &b); 55 ptr[i]->link(ptr[b], 1); 56 } else { 57 ; 58 } 59 if (ptr[i]->f == null) root = ptr[i]; 60 } 61 } 62 inline void bfs(){ 63 queue<Node *> que; 64 vector<int> ans; 65 que.push(root); 66 while (!que.empty()){ 67 Node *x = que.front(); 68 que.pop(); 69 ans.push_back(x->v); 70 if (x->ch[0] != null) que.push(x->ch[0]); 71 if (x->ch[1] != null) que.push(x->ch[1]); 72 } 73 int n = ans.size(); 74 for (int i = 0; i < n; i++){ 75 printf("%d%c", ans[i], i < n - 1 ? ' ' : ' '); 76 } 77 } 78 }tree; 79 int main(){ 80 #ifdef LOCAL 81 freopen("in.txt", "r", stdin); 82 freopen("out.txt", "w+", stdout); 83 #endif 84 int n; 85 while (~scanf("%d", &n)){ 86 tree.init(), tree.gogo(n), tree.bfs(); 87 } 88 return 0; 89 }