标签:
题目描述:
如果序列相同则输出YES,否则输出NO
2 567432 543267 576342 0
YES NO
在九度oj上Pending了两天,今天终于能用了,终于一次就AC了,代码如下:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <string> 5 6 /* 7 0 8 1 2 9 3 4 5 6 10 7 8 9 10 11 12 13 14 11 12 */ 13 void buildTree(int n,int num[],int tree[],int left[],int right[]) { 14 for(int i = 0; i < 10; i++) { 15 tree[i] = -1; 16 left[i] = -1; 17 right[i] = -1; 18 } 19 int top = num[0]; 20 tree[top] = 0; 21 for(int i = 1; i < n; i++) { 22 top = num[0]; 23 int address = 0; 24 while(true) { 25 if(num[i] < top) { 26 address = 2 * address + 1; 27 if(left[top] == -1) { 28 left[top] = num[i]; 29 tree[num[i]] = address; 30 break; 31 } 32 else { 33 top = left[top]; 34 } 35 } 36 else if(num[i] > top) { 37 address = 2 * address + 2; 38 if(right[top] == -1) { 39 right[top] = num[i]; 40 tree[num[i]] = address; 41 break; 42 } 43 else { 44 top = right[top]; 45 } 46 } 47 }//while 48 49 } 50 } 51 52 char s[20]; 53 int main(int argc, char const *argv[]) 54 { 55 int n; 56 int len; 57 scanf("%d",&n); 58 while(n != 0) { 59 int num[12];//source 60 int tree[12];//every num‘s address 61 int left[12];//every num‘s nextLeft‘s value 62 int right[12];//every num‘s nextRight‘s value 63 scanf("%s",s); 64 for(int i = 0; i < strlen(s); i++) { 65 num[i] = s[i] - ‘0‘; 66 } 67 buildTree(strlen(s),num,tree,left,right); 68 len = strlen(s); 69 for(int i = 0; i < n; i++) { 70 scanf("%s",s); 71 int numt[12];//source 72 int treet[12];//every num‘s address 73 int leftt[12];//every num‘s nextLeft‘s value 74 int rightt[12];//every num‘s nextRight‘s value 75 for(int i = 0; i < strlen(s); i++) { 76 numt[i] = s[i] - ‘0‘; 77 } 78 buildTree(strlen(s),numt,treet,leftt,rightt); 79 bool flag = true; 80 if(strlen(s) != len) { 81 flag = false; 82 } 83 for(int i = 0; i < strlen(s) && flag == true; i++) { 84 if(treet[numt[i]] != tree[numt[i]]) { 85 flag = false; 86 break; 87 } 88 } 89 if(flag == false) { 90 printf("%s\n","NO"); 91 } 92 else { 93 printf("%s\n","YES"); 94 } 95 } 96 scanf("%d",&n); 97 } 98 return 0; 99 }
这道题的思路是用数组记录建好树后每一个数字的位置,通过比较位置信息来判断是不是同一棵树
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5669167.html