题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
AC代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<cmath>
using namespace std;
char ss[][];
#define MAX 27
struct trie
{
trie *next[MAX];
int v;
trie()
{
int i;
v=;
for(i=; i<; i++) next[i]=NULL;
}
};
trie *p,*q;
void creattrie(char *str,trie *root)
{
int len = strlen(str);
p = root;
for(int i=;i<len; i++)
{
int id = str[i] - 'a';
if(p->next[id] == NULL)
{
q=new trie;
q->v = ;
p->next[id] = q;
p=q;
}
else
{
p=p->next[id];
p->v+=;
}
}
}
int findtrie(char *str,trie *root)
{
int i;
int len = strlen(str);
p = root;
for(i=;i<len;i++)
{
int id = str[i] - 'a';
p=p->next[id];
if(p->v == )
{
return i+;
}
}
}
int main()
{
int T,n,ans;
scanf("%d",&T);
while(T--)
{
ans = ;
trie *root = new trie;
scanf("%d",&n);
//getchar();
for(int i=;i<n;i++)
{
scanf("%s", ss[i]);//用gets接收错了一天了,晚上才发现
creattrie(ss[i],root);
}
for(int i=;i<n;i++)
{
int kk = findtrie(ss[i],root);
ans = ans+kk;
}
printf("%d\n",ans);
}
return ;
}