九度 oj 题目1090:路径打印

62 篇文章 0 订阅
12 篇文章 0 订阅

http://ac.jobdu.com/problem.php?pid=1090


使用二叉树表示多叉树。 在每层找对应的文件名,如果没有就新建。然后继续向下查找(或创建)。

#include <iostream>
#include <string>
using namespace std;

typedef struct node{ 
    string name; 
    struct node * first_child;
    struct node * next_sibling;
}Node; 

Node* createNode(string name){ 
    Node* n = new Node; 
    n->name = name; 
    n->first_child = NULL;
    n->next_sibling = NULL;
    return n;
} 

void build(Node *root, string path){ 
    if (path =="") return ;
    string::size_type idx = path.find("\\");  
    if(idx == string::npos) idx = path.length(); 
    string name = path.substr(0,idx); //child name 
    if(idx!=path.length()) idx++;
    path = path.substr(idx); //left path
    Node * ch,*pre;
    bool exist = false;
    //find right place for child
    for (ch = root->first_child, pre=root; ch!=NULL; pre=ch,ch=ch->next_sibling ) { 
        if(ch->name == name){ 
            exist = true;
            break;
        }else if(ch->name > name){ 
            break; 
        }     
    }
    if(exist){ 
        build(ch,path);  
    }else{ 
        Node* newNode = createNode(name);
        if(pre == root){ 
            pre->first_child = newNode;  
        }else{ 
            pre->next_sibling = newNode; 
        }    
        newNode->next_sibling = ch;
        build(newNode,path); 
    }  
}  

void destroy(Node * root){ 
    if(root == NULL) return;  
    destroy(root->first_child);
    destroy(root->next_sibling); 
    delete root;
} 

void dfs(Node * root,int addLen){ 
    if(root == NULL) return ;  
    for (int i = 0; i < addLen; ++i) cout<<" "; 
    if(root->name !="") cout<<root->name<<endl; 
    if(root->first_child) dfs(root->first_child,(int)root->name.length()+addLen+1); 
    if(root->next_sibling) dfs(root->next_sibling,addLen);  

}  
int main(){ 
    //freopen("in/1090.in","r",stdin); 
    //freopen("out/1090.out","w",stdout); 
    int n; 
    string path;
    while(cin>>n && n!=0){ 
        Node * root = createNode(""); 
        while(n--){ 
            cin>>path; 
            build(root,path); 
        }  
        dfs(root,-1); 
        cout<<endl;
        destroy(root);
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值