题目:poj2001
题意:寻找最长公共前缀
解答:大概是最简单的字典树的建立、查找
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
const int sonnum = 26,base = 'a';
char a[10010][26];
using namespace std;
struct Trie//定义字典树的节点
{
int num;
bool terminal;
struct Trie *son[sonnum];
};
Trie *NewTrie()//建立一个字典树
{
Trie *temp = new Trie;///
temp -> num = 1;
temp -> terminal = false;
for(int i = 0;i < sonnum;i++)
temp -> son[i] = NULL;
return temp;
}
void Insert(Trie *pnt,char *s,int len)//插入单词
{
Trie *temp = pnt;
for(int i = 0;i < len;i++)
{
if(temp -> son[s[i]-base] == NULL)
temp -> son[s[i]-base] = NewTrie();///
else
temp -> son[s[i]-base] -> num++;
temp = temp -> son[s[i]-base];
}
temp -> terminal = true;
}
Trie *Find(Trie *pnt,char *s,int len)//查找单词
{
Trie *temp = pnt;
for(int i = 0;i < len;i++)
{
if(temp -> son[s[i]-base] -> num == 1)
{
printf("%c",s[i]);
return temp;
}
printf("%c",s[i]);
temp = temp -> son[s[i]-base];
}
return temp;
}
int main()
{
int cnt = 0;
char t[110];
Trie *tree = NewTrie();///
while(~scanf("%s",a[cnt]))
{
if(a[cnt][0] == '0')
break;
Insert(tree,a[cnt],strlen(a[cnt]));
cnt++;
}
for(int i = 0;i < cnt;i++)
{
printf("%s ",a[i]);
Find(tree,a[i],strlen(a[i]));
printf("\n");
}
return 0;
}