最短的名字

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

#include<string.h>
#include<malloc.h>
#include<stdio.h>
typedef struct node
{
	int count;
	struct node *next[26];
}*tree;
void insert(tree h,char *s)
{
	tree p=h;
	int len=strlen(s),i;
	for(i=0;i<len;i++)
	{
		int index=s[i]-'a';
		if(p->next[index]!=NULL)
		{
			p=p->next[index];
			p->count++;
		}
		else
		{
			tree tem=(tree)calloc(1,sizeof(node));
			tem->count=1;
			p->next[index]=tem;
			p=tem;
		}
	}
}
int find(tree h)
{
	tree q;
	int sum=0,i;
	q=h;
	for(i=0;i<26;i++)
    {
        if(h->next[i]!=NULL)
        {
            q=h->next[i];
            sum+=q->count;
            if(q->count>1)
            {
                sum+=find(q);
            }
        }
    }
    return sum;
}
void release(tree h)
{
	int i;
    for(i=0;i<26;i++)
        if(h->next[i]!=NULL)
        release(h->next[i]);
    free(h);
}
int main()
{
	//freopen("b.txt","r",stdin);
	char s[1110];
	int t,n,i;
	scanf("%d",&t);
	while(t--)
    {
        tree head=(tree)calloc(1,sizeof(node));
        scanf("%d\n",&n);
        for(i=0;i<n;i++)
        {
        scanf("%s",s);
		insert(head,s);
        }
	//while(scanf("%s",s)==1)
	//{
		//int num=find(head,s);
		printf("%d\n",find(head));
		release(head);
	//}
    }
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值