#1551 : 统计子目录
时间限制:
10000ms
单点时限:
1000ms
内存限制:
256MB
-
3 /hihocoder/offer22/solutions/p1 /hihocoder/challenge30/p1/test /game/moba/dota2/uninstall
样例输出
-
8
描述
小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
输出
一个整数代表不同子目录的数目。
思路:
建一个字典树,然后统计其中 “/”的个数就是答案了
**#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;
}
**