字典树模板套用,带有一点贪心的思想。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int MAX=26;
typedef struct TrieNode
{
struct TrieNode *next[MAX]; //该节点的后续节点
} TrieNode;
TrieNode Memory[1000000]; //先分配好内存。 malloc 较为费时
int allocp = 0;
int ans;
//初始化一个节点。nCount计数为1, next都为null
TrieNode * createTrieNode()
{
TrieNode * tmp = &Memory[allocp++];
for (int i = 0; i < MAX; i++)
tmp->next[i] = NULL;
return tmp;
}
void insertTrie(TrieNode * pRoot, char * str)
{
TrieNode * tmp = pRoot;
int i = 0, k;
//一个一个的插入字符
while (str[i])
{
k = str[i] - 'a'; //当前字符 应该插入的位置
if (tmp->next[k])
{
}
else
{
tmp->next[k] = createTrieNode();
ans++;
}
tmp = tmp->next[k];
i++; //移到下一个字符
}
}
int main(void)
{
char s[55];
int T;
int i;
int length,m;
while(scanf("%d",&T)!=EOF)
{
ans=0;
allocp=0;
TrieNode * Root = createTrieNode();
m=0;
for(i=0;i<T;i++)
{
scanf("%s",s);
insertTrie(Root,s);
if(m<strlen(s))
m=strlen(s);
}
printf("%d\n",ans*2-m+T);
}
return 0;
}