hdu 5444 Elven Postman(根据先序遍历和中序遍历求后序遍历)2015 ACM/ICPC Asia Regional Changchun Online...
很坑的一道題,讀了半天才讀懂題,手忙腳亂的寫完(套上模板+修改模板),然后RE到死……
題意:
題面上告訴了我們這是一棵二叉樹,然后告訴了我們它的先序遍歷,然后,沒了……沒了!
反復(fù)讀題,終于在偶然間注意到了這一句——"Not only that, when numbering the rooms, they always number the room number from the east-most position to the west."
它告訴我們,東邊的點總是比西邊的點小——也就是說,這個樹的中序遍歷是從1到n的一個等差數(shù)列……
?
輸入:
首行輸入一個整數(shù)t,表示有t組數(shù)據(jù);
接下來每組數(shù)據(jù)首行一個整數(shù)n,表示有這棵樹有n個節(jié)點。
接下來一行有n個整數(shù),表示這棵樹的先序遍歷。
接下來一行一個整數(shù)m,表示m次查詢。
接下來一行有m個整數(shù),表示每次查詢的點。
?
輸出:
每次查詢輸出從根節(jié)點到查詢節(jié)點的路徑,路徑中,每次向左輸出'E',每次向右輸出'W'。
?
解題思路:
套上模板,建立起這棵樹,同時用一個fm[]數(shù)組講每個節(jié)點的父節(jié)點記錄下來。然后查詢的時候使用就行了。
?
但是有兩點需要注意:
1. 由于我是使用指針建立的樹,所以每用完一組數(shù)據(jù)都要記得釋放內(nèi)存!
2. 每次第二組數(shù)據(jù)的根節(jié)點也許在第一組數(shù)據(jù)中不是根節(jié)點,所以要記得將根節(jié)點的父節(jié)點fm[root]置為0。我的現(xiàn)場賽名額啊……因此離我而去T_T,555555……
不說了,說多了都是淚。。。。。
上代碼——
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include <cmath> 5 #include <algorithm> 6 using namespace std; 7 8 struct Node 9 { 10 int c; 11 Node *left; 12 Node *right; 13 }; 14 15 int fm[1010]; 16 int t, n, m; 17 char dis[1010]; 18 int pree[1010],ine[1010]; 19 20 Node* BuildTree(int *pre, int *in, int length) //建樹 21 { 22 if(length == 0) return NULL; 23 Node* node = (Node*) malloc(sizeof(Node)); 24 node->c = pre[0]; 25 int rootindex = -1; 26 for(int i = 0;i < length;i++) 27 { 28 if(in[i] == pre[0]) 29 { 30 rootindex = i; 31 break; 32 } 33 } 34 node->left = BuildTree(pre+1,in,rootindex);//left 35 node->right = BuildTree(pre+1+rootindex,in+rootindex+1,length-rootindex-1);//right 36 return node; 37 } 38 39 void print(Node *root) //記錄父節(jié)點 40 { 41 if(root != NULL) 42 { 43 if(root->left != NULL) fm[root->left->c] = (root->c)*10; 44 print(root->left); 45 if(root->right != NULL) fm[root->right->c] = (root->c)*10+1; 46 print(root->right); 47 } 48 } 49 50 void dfs(Node* root) //釋放內(nèi)存 51 { 52 if(root != NULL) 53 { 54 if(root->left != NULL) dfs(root->left); 55 if(root->right != NULL) dfs(root->right); 56 free(root); 57 } 58 } 59 60 int main() 61 { 62 //freopen("test.in", "r", stdin); 63 scanf("%d", &t); 64 while(t--) 65 { 66 scanf("%d", &n); 67 for(int i = 0; i < n; i++) 68 { 69 scanf("%d", &pree[i]); 70 ine[i] = i+1; 71 } 72 Node *root = BuildTree(pree, ine, n) ; 73 fm[root->c] = 0; //就是這里,坑死我了……我@#¥%^&*! 74 print(root); 75 scanf("%d",&m); 76 for(int i = 0; i < m; i++) 77 { 78 int mid; 79 scanf("%d", &mid); 80 int k = 0; 81 while(fm[mid] != 0) 82 { 83 if(fm[mid]%10 == 1) dis[k] = 'W'; 84 else dis[k] = 'E'; 85 mid = fm[mid]/10; 86 k++; 87 } 88 for(int j = k-1; j >=0; j--) printf("%c", dis[j]); //輸出路徑 89 printf("\n"); 90 } 91 dfs(root); 92 } 93 return 0; 94 } View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/mypride/p/4814787.html
總結(jié)
以上是生活随笔為你收集整理的hdu 5444 Elven Postman(根据先序遍历和中序遍历求后序遍历)2015 ACM/ICPC Asia Regional Changchun Online...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 表单隐藏域与display:none
- 下一篇: 【linux】使用swap文件恢复非正常