hihoCoder 1383 : The Book List

    xiaoxiao2023-03-25  6

    参考代码: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); } }

    转载请注明原文地址: https://ju.6miu.com/read-1203739.html
    最新回复(0)