每日一題之 hiho 1551 統計子目錄

#1551 : 統計子目錄

時間限制:10000ms
單點時限:1000ms
內存限制:256MB

描述

小Hi的電腦的文件系統中一共有N個文件,例如:

/hihocoder/offer22/solutions/p1

/hihocoder/challenge30/p1/test  

/game/moba/dota2/uninstall  

小Hi想統計其中一共有多少個不同的子目錄。上例中一共有8個不同的子目錄:

/hihocoder

/hihocoder/offer22

/hihocoder/offer22/solutions

/hihocoder/challenge30

/hihocoder/challenge30/p1

/game

/game/moba

/game/moba/dota2/

輸入

第一行包含一個整數N (1 ≤ N ≤ 10000)  

以下N行每行包含一個字符串,代表一個文件的絕對路徑。保證路徑從根目錄"/"開始,並且文件名和目錄名只包含小寫字母和數字。  

對於80%的數據,N個文件的絕對路徑長度之和不超過10000  

對於100%的數據,N個文件的絕對路徑長度之和不超過500000

輸出

一個整數代表不同子目錄的數目。

樣例輸入
3  
/hihocoder/offer22/solutions/p1   
/hihocoder/challenge30/p1/test  
/game/moba/dota2/uninstall
樣例輸出
8

思路:

建一個字典樹,然後統計其中 “/”的個數就是答案了

**#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>

using namespace std;

const int maxn = 37;

struct Trie 
{
     Trie *next[maxn]; //下一層的節點數(小寫字母個數)
     int v; //從根節點到當前節點爲前綴的單詞個數
     Trie(){}
};

Trie root;
int res;
void creatTrie(string s)
{
    int len = s.length();
    Trie *p = &root;
    Trie *q;

    for (int i = 0; i < len; ++i) { //對單詞s建立字典樹
        int id;
        if (s[i] >= 'a' && s[i] <= 'z')
            id = s[i] - 'a';
        else if (s[i] >= '0' && s[i] <= '9')
            id = s[i] - '0' + 26;
        else if (s[i] == '/')
            id = 36;
        if (p->next[id] == nullptr) {
            q = new Trie();
            for (int j = 0; j < maxn; ++j)
                q->next[j] = nullptr;
            q->v = 1; 
            p->next[id] = q;
        }
        else {
            p->next[id]->v++;
        }
        if (id == 36 && p->next[id]->v == 1) ++res;
        p = p->next[id];

    }

}
int main()
{

    int n,m;
    cin >> n;
    string s;
    res = 0;
    for (int i = 0; i < n; ++i) {
        cin >> s;
        s = s.substr(1,s.length());
        //cout << s << endl;
        creatTrie(s);
    }
    cout << res << endl;


    return 0;
}

**
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章