九度1090-路径打印-多叉树

来源:互联网 发布:windows黑体字体下载 编辑:程序博客网 时间:2024/05/17 23:20

这道题真的是巨坑!调了将近一个小时的格式才发现要按照前面父目录的字符串长度进行缩进


附上PE6发之后好不容易AC的代码:

#include<bits/stdc++.h>using namespace std;//多叉树 typedef struct Node{char s[60];Node *son;Node *next_sibling;}Node;Node node[30]; void DFS(Node *root, int depth){Node *p = root->son;while(p){for(int i = 1; i <= depth; i++){cout << " "; }int len = strlen(p->s);cout << p->s << endl;DFS(p, depth+1+len);//这里输出格式一定要注意!!p = p->next_sibling;}}int main(){int n;while(~scanf("%d", &n) && n){Node *rt = new Node();rt->son = NULL;rt->next_sibling = NULL;while(n--){char s[60];scanf("%s", s);int len = strlen(s);char tmp[60];memset(tmp, 0, sizeof(tmp));int flag = 0;Node *p = rt;for(int i = 0; i <= len-1; i++){if(s[i] != '\\'){tmp[flag++] = s[i];}if(s[i] == '\\' || i == len-1){if(p->son == NULL){Node *tt = new Node();strncpy(tt->s, tmp, flag);tt->son = NULL;tt->next_sibling = NULL;p->son = tt;p = tt;}else{Node *pre = p;p = p->son;while(p && strcmp(p->s, tmp) < 0){//printf("%s %s\n", p->s, tmp);pre = p;p = p->next_sibling;}if(p == NULL){Node *tt = new Node();    strncpy(tt->s, tmp, flag);    tt->son = NULL;    tt->next_sibling = NULL;    pre->next_sibling = tt;    p = tt;    //printf("aa\n");}else if(strcmp(p->s, tmp) > 0){Node *tt = new Node();    strncpy(tt->s, tmp, flag);    tt->son = NULL;    tt->next_sibling = p;    if(p == pre->son)       pre->son = tt;    else if(p == pre->next_sibling)       pre->next_sibling = tt;    p = tt;}    //等于节点值的只需要找到这个节点 }memset(tmp, 0, sizeof(tmp));flag = 0;}//printf("i:%d s[i]:%c\n", i, s[i]);}}DFS(rt, 0);cout << endl;}return 0;}


原创粉丝点击