2015年5月29日星期五

[UVa] 10562 - Undraw the Tree

主要以深度優先搜尋DFS,遞迴整棵樹,邊遞迴邊輸出



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cctype>
char tree[300][300];
int k=0; //the high of the input tree
void dfs(int r,int c){
 printf("%c(",tree[r][c]);
 if(r+1<k && tree[r+1][c]=='|'){ //邊界要注意
  int i=c;
  while(i-1>=0 && tree[r+2][i-1]=='-')i--;
  while(tree[r+2][i]=='-' && tree[r+3][i]!='\0'){
   if(tree[r+3][i]!=' ' && tree[r+3][i]!='\n')dfs(r+3,i); 
   //上面這邊一定要判斷換行和空白
   i++;
  }
 }
 printf(")");
}
int main(){
 freopen("input.txt","r",stdin);
 int T;
 scanf("%d",&T);
 getchar();
 while(T--){
  memset(tree,0,sizeof(tree));
  k=0;
  while(fgets(tree[k],sizeof(tree[k]),stdin)){
   //printf("%s",tree[k]);
   if(tree[k][0]=='#')break;
   else k++;
  }
  printf("(");
  if(k){
   for(int i=0;i<strlen(tree[0]);i++){
    if(tree[0][i]!=' '){ //這邊也是要以空白為判斷
     //printf("%c\n",tree[0][i]);
     dfs(0,i);
     break;
    }
   }
  }
  printf(")\n");
 }
 return 0;
}

沒有留言: