您的位置:首页 > 其它

poj -- 2001 Shortest Prefixes (Trie 树)

2015-06-20 16:18 288 查看
题目大意:



求一字符串在一堆字符串中的能被辨别的最短前缀;

代码实现:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
char str[1005][25];

struct tree{
int cnt;
tree *next[26];
}*root;

tree *Create(){
tree *p;
p=(tree *)malloc(sizeof(tree));
p->cnt=0;
for(int i=0;i<26;++i) p->next[i]=NULL;
return p;
}

void Insert(char *s){
int i=0,x,l=strlen(s);
tree *p=root;
while(i<l){
x=s[i++]-'a';
if((p->next[x])==NULL) p->next[x]=Create();
p=p->next[x];
p->cnt++;
}
}

void Search(char *s){
tree *p=root;
int i=0,x,l=strlen(s);
while(i<l){
printf("%c",s[i]);
x=s[i++]-'a';
p=p->next[x];
if((p->cnt)==1) break;
}
printf("\n");
}

int main(){
int n=0;
root=Create();
while(~scanf("%s",str
)){
Insert(str
);
n++;
}
for(int i=0;i<n;++i){
printf("%s ",str[i]);
Search(str[i]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: