您的位置:首页 > 其它

POJ2001 Shortest Prefixes 动态字典树实现

2017-08-04 20:06 471 查看
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;

struct node{
int word;
struct node *next[30];
node();
};

node::node(){
memset(next,0,sizeof(next));
word=0;
}

struct node *head=new node;
string word[1010];

void add(string s){
struct node *p,*q;
p=head;
for(int i=0;i<s.length();i++){
int to=s.at(i)-'a';
if(i!=s.length()){
if(p->next[to]==NULL){
p->next[to]=new node;
}
p=p->next[to];
p->word=p->word+1;
}
}
}

void getMin(string s){
struct node *p;
p=head;
for(int i=0;i<s.length();i++){
int to=s.at(i)-'a';
cout<<s.at(i);
if(i+1!=s.length()){
if(p->next[to]==NULL)
return;
if(p->next[to]->word==1)
return;
p=p->next[to];
}
}
}

int main(){
int n=0;
while(!cin.eof()){
cin>>word
;
add(word
);
n++;
}
n--;
for(int i=0;i<n;i++){
cout<<word[i]<<" ";
getMin(word[i]);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字典树 poj