hihoCoder 1383 : The Book List

參考代碼: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);
    }
}


發佈了257 篇原創文章 · 獲贊 148 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章