最短的名字
Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
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
用字典树。后面还有一个参考答案代码,很短。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1001][10001];
struct node
{
int v;
char now;
node *next[26];
};
node root;
void biuld(char *str) //创建字典树
{
int i,len;
len = strlen(str);
node *p = &root,*q;
for(i = 0; i < len; i++)
{
int id = str[i]-'a';
if(p->next[id]==NULL)
{
q=(node *)malloc(sizeof(root));
q->v = 1;
for(int j = 0; j < 26; j++)
{
q->next[j] = NULL;
}
p->next[id] = q;
p=p->next[id];
}
else
{
p->next[id]->v++;
p=p->next[id];
}
}
}
/*void Dfs(int k,)
{
}*/
int findTrie(char *str)
{
int i;
int len=strlen(str);
node *p=&root;
for(i=0;i<len;i++)
{
int id=str[i]-'a';
p=p->next[id];
if(p->v<=1)
{
return i+1;
}
}
return i;
}
int main()
{
int sum;
int t,n,i;
scanf("%d",&t);
while(t--)
{
for(i = 0; i < 26; i++) //重置根节点
{
root.next[i] = NULL;
}
sum = 0;
scanf("%d",&n);
for(i = 0; i < n; i++)
{
scanf("%s",&s[i]);
biuld(s[i]);
}
for(i = 0; i < n; i++)
{
sum+=findTrie(s[i]);
}
printf("%d\n",sum);
}
return 0;
}
参考代码:
// Yiming Li
#include<cstdio>
#include<cstring>
#include<vector>
#include<string>
#include<algorithm>
#include<cassert>
using namespace std;
vector<string> a;
char s[1010000];
int d[2000];
int main()
{
int i,j,l,t,n,ans;
scanf("%d",&t);
assert(t<=10);
for (l=0;l<t;l++)
{
scanf("%d",&n);
assert(1<=n&&n<=1000);
a.clear();
int tot = 0;
for (i=0;i<n;i++)
{
scanf("%s",s);
tot += strlen(s);
a.push_back(s);
}
assert(tot <= 1000000);
sort(a.begin(),a.end());
memset(d,0,sizeof(d));
for (i=0;i+1<n;i++)
{
for (j=0;j<a[i].length()&&j<a[i+1].length();j++)
if (a[i][j]!=a[i+1][j]) break;
if (j+1>d[i]) d[i]=j+1;
if (j+1>d[i+1]) d[i+1]=j+1;
}
ans=0;
for (i=0;i<n;i++)
ans+=d[i];
printf("%d\n",ans);
}
return 0;
}