POJ_2001_trie
来源:互联网 发布:成都德州仪器知 编辑:程序博客网 时间:2024/05/21 11:26
//============================================================================
// Name : POJ_2001.cpp
// Author : tiger
// Version :
// Copyright : Your copyright notice
// Description : 可能有相同单词的情况
//============================================================================
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct NODE
{
int n;
bool f;
NODE *next[27];
void intial()
{
for (int i = 0; i < 27; i++)
{
next[i] = NULL;
}
n = 0;
f = false;
}
};
NODE pool[26 * 1001];
int counts;
void insert(NODE *root, char *s)
{
root -> n = root -> n + 1;
if (*s == 0)
{
root->f = true;
return;
}
if (root->next[*s - 'a'] == NULL)
{
root->next[*s - 'a'] = pool + counts++;
root->next[*s - 'a']->intial();
}
insert(root->next[*s - 'a'], s + 1);
}
bool find(NODE *root, char *s)
{
if (*s == 0 )
{
if( root->f == true)
return true;
return false;
}
if (root->next[*s - 'a'] == NULL)
{
return false;
}
return find(root->next[*s - 'a'], s + 1);
}
int display(NODE *root, char *s, int n)
{
if (root-> n == 1 || *s == 0)
return n;
return display(root->next[*s - 'a'], s + 1, ++n);
}
int main()
{
freopen("in", "r", stdin);
char s[1002][25];
int i, n;
n = 0;
counts = 0;
NODE *root = pool + counts++;
root->intial();
while (scanf("%s", s[n]) != EOF)
{
if (find(root, s[n]) == false)
{
insert(root, s[n]);
}
n++;
}
for (i = 0; i < n; i++)
{
printf("%s ", s[i]);
s[i][display(root, s[i], 0)] = 0;
printf("%s/n", s[i]);
}
return 0;
}