hihoCoder 1383 : The Book List

11 篇文章 0 订阅

参考代码:http://blog.csdn.net/xzxxzx401/article/details/52662869


编码能力,STL灵活运用,递归。

用Map构造层次结构,构建了类似链表的结构,Map<string,Node>

每一层有一个set,只储存了层次结构中倒数第二个节点后面的节点

当前能用Map存的,用Map存下了,剩下的丢到了set里,这样在输出的时候就能先输出有子节点的,再输出没有子节点的,而且都是按照字典序。


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <stack>
using namespace std;

const int oo=0x3f3f3f3f;
const int MAXN=22007;
typedef long long LL;
struct Node{
    map<string,Node>cat; // 构造string的链表
    set<string>book;
    Node(){}
};
void Insert(Node &now,string s){
    int pos = s.find_first_of('/');
    string s_front,s_back;
    bool is_book = 0;
    if(pos == string::npos){
        s_front = s;
        is_book = 1;
    }
    else{
        s_front = s.substr(0,pos);
        s_back = s.substr(pos+1);
    }
    if(is_book){
        now.book.insert(s_front);
        return;
    }
    else{
        if(now.cat.count(s_front) == 0){
            now.cat[s_front] = Node();
        }
        //递归
        Insert(now.cat[s_front],s_back);
    }
}
void print(Node &now,int level){
    map<string,Node>::iterator it = now.cat.begin();
    for(;it!=now.cat.end();it++){
        for(int i=0;i<level;i++) printf("    ");
        cout<<(it->first)<<endl; //在Map中的就直接输出了,
        print(it->second,level+1);
    }
    //剩下的在set中输出
    set<string>::iterator it1 = (now.book.begin());
    for(;it1!=now.book.end();it1++){
        for(int i=0;i<level;i++) printf("    ");
        cout<<(*it1)<<endl;
    }
}
int main(){
    int ca = 1;
    string s;
    while(getline(cin,s)){
        Node head;
        Insert(head,s);
        while(getline(cin,s)){
            if(s == "0" ) break;
            Insert(head,s);
        }
        cout<<"Case "<<ca<<":"<<endl;
        ca++;
        print(head,0);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值