Trie树,每个结点记录其下面分支的单词总数。
View Code
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
struct Node
{
Node *next[26];
int count;
} trie[100000];
int ncount;
void ins(Node *proot, char *st)
{
proot->count++;
if (st[0] == '\0')
return;
if (!proot->next[st[0] - 'a'])
{
ncount++;
proot->next[st[0] - 'a'] = trie + ncount;
}
ins(proot->next[st[0] - 'a'], st + 1);
}
void query(Node *proot, char *st)
{
if (st[0] == '\0')
return;
printf("%c", st[0]);
if (proot->next[st[0] - 'a']->count > 1)
query(proot->next[st[0] - 'a'], st + 1);
}
int main()
{
//freopen("t.txt", "r", stdin);
ncount = 0;
char st[1005][30];
memset(trie, 0, sizeof(trie));
int i = 0;
while (scanf("%s", st[i]) != EOF && strlen(st[i]) != 0)
{
ins(trie, st[i]);
i++;
}
int n = i;
for (i = 0; i < n; i++)
{
printf("%s ", st[i]);
query(trie, st[i]);
printf("\n");
}
return 0;
}