最短的名字
Description
在一个奇怪的村子中,很多人的名字都很长,比如aaaaa, bbb and abababab。
名字这么长,叫全名显然起来很不方便。所以村民之间一般只叫名字的前缀。比如叫'aaaaa'的时候可以只叫'aaa',因为没有第二个人名字的前三个字母是'aaa'。不过你不能叫'a',因为有两个人的名字都以'a'开头。村里的人都很聪明,他们总是用最短的称呼叫人。输入保证村里不会有一个人的名字是另外一个人名字的前缀(作为推论,任意两个人的名字都不会相同)。
如果村里的某个人要叫所有人的名字(包括他自己),他一共会说多少个字母?
Input
输入第一行为数据组数T (T<=10)。每组数据第一行为一个整数n(1<=n<=1000),即村里的人数。以下n行每行为一个人的名字(仅有小写字母组成)。输入保证一个村里所有人名字的长度之和不超过1,000,000。
Output
对于每组数据,输出所有人名字的字母总数。
Sample Input
1
3
aaaaa
bbb
abababab
Sample Output
5
思路: 字典树 dfs查询 第一次写字典树有些熟练啊
ACcode:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 1000010
int clk, ans, cnt[N], ch[N][26];
char s[N];
void insert(int root,char s[])
{
cnt[root]++;
for (int i = 0; s[i]!='\0' ; i++)
{
if (ch[root][s[i] - 'a'] == 0)
{
ch[root][s[i] - 'a'] = ++clk;
root = ch[root][s[i] - 'a'];
memset(ch[root], 0, sizeof(ch[root]));
cnt[root] = 1;
}
else
{
root = ch[root][s[i] - 'a'];
cnt[root]++;
}
}
}
void dfs(int root, int t)
{
if (cnt[root] == 1)
{
ans += t;
return;
}
for (int i = 0; i < 26; i++)
{
if (ch[root][i] != 0)
dfs(ch[root][i], t + 1);
}
}
int main()
{
int t,n;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
clk = 0;
ans = 0;
memset(ch[0], 0, sizeof(ch[0]));
for (int i = 1; i <= n; i++)
{
scanf("%s", s);
insert(0, s);
}
dfs(0, 0);
printf("%d\n", ans);
}
}