您的位置:首页 > 其它

CSU 1115 最短的名字

2015-08-10 20:55 435 查看
在一个奇怪的村子中,很多人的名字都很长,比如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


#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;

typedef struct zc
{
int count;
struct zc *next[26];
}node;

node *T;
char a[1001000];
node *newnode()
{
node *p;
p=(node*)malloc(sizeof(node));
p->count=1;
for(int i=0;i<26;i++)
{
p->next[i]=NULL;
}
return p;
}

void build(node* T,char s[])
{
node *q,*p=T;
int len=strlen(s),k;
for(int i=0;i<len;i++)
{
k=s[i]-'a';
if(p->next[k]==NULL)
{
p->next[k]=newnode();
p=p->next[k];
}
else
{
p=p->next[k];
p->count++;
}

}
}

void Release(node *T)
{
for(int i=0;i<26;i++)
{
if(T->next[i]!=NULL)
{
Release(T->next[i]);
}
}
free(T);
}

int search(node *T)
{
node *q=T;
int sum=0;
for(int i=0;i<26;i++)
{
if(T->next[i]!=NULL)
{
q=T->next[i];
sum+=q->count;
if(q->count>1)
{
sum+=search(q);
}
}
}
return sum;
}

int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
T=(node*)malloc(sizeof(node));
T->count=0;
for(int i=0;i<26;i++)
T->next[i]=NULL;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",a);
build(T,a);
}
printf("%d\n",search(T));
Release(T);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: