标签:option bad 简单 个人 img eof ble turn .com
转载请注明:
题目大意:
题目传送门:UVa 10562 Undraw the Trees
给定字符拼成的树,将这些树转换成特定的括号表示的树
思路:
首先,观察样例,可以发现就是先序遍历的顺序,因此可以确定dfs
但是,还有几个地方需要考虑:
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 5 const int SIZE = 200 + 10; 6 char tree[SIZE][SIZE]; 7 8 int num = 0; // tree num 9 int cur = 0; // cur num of row in tree 10 11 bool valid_node(char ch); 12 void dfs_tree(int row, int col); 13 14 int main(){ 15 // use fgets() and sscanf() to read white char and then remove them. 16 fgets(tree[0], SIZE, stdin); 17 sscanf(tree[0], "%d", &num); 18 while(num--){ 19 // read tree 20 cur = 0; 21 // memset is compulsory because the ‘|‘ behind the ‘\0‘ of the last tree will 22 // have a bad influence on current tree 23 memset(tree, 0, sizeof(tree)); 24 // use fgets() instead of gets() to read tree in order to avoid overflow 25 while(fgets(tree[cur], SIZE, stdin) != NULL && tree[cur][0] != ‘#‘)cur++; 26 // dfs - for the condition of forest 27 printf("("); 28 for(int i=0; tree[0][i]; i++) 29 if(valid_node(tree[0][i])) 30 dfs_tree(0, i); 31 // postprocess. If we use "if(num > 0)puts("");", it will cause "wrong answer" 32 printf(")\n"); 33 } 34 } 35 36 bool valid_node(char ch){ 37 return strchr("-| #\n", ch) == NULL; // we need add ‘\n‘ because fegets() will read the ‘\n‘ at end of each line to the tree. 38 } 39 40 void dfs_tree(int row, int col){ 41 printf("%c(", tree[row][col]); // print root of the tree, and then print ‘(‘ 42 if(row < cur && tree[++row][col] == ‘|‘){ 43 int i=col; 44 row++; 45 while(i - 1 >= 0 && tree[row][i-1] == ‘-‘)i--; // left bouder of "---" 46 for(;tree[row][i] == ‘-‘; i++) 47 if(valid_node(tree[row+1][i])) dfs_tree(row+1, i); 48 } 49 printf(")"); 50 }
啦啦啦,今天就到这里啦~改天见*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。
UVa 10562 Undraw the Trees 看图写树
标签:option bad 简单 个人 img eof ble turn .com
原文地址:http://www.cnblogs.com/luruiyuan/p/7291323.html