字典树的题,敲过一两道基本上就会了。(我这里出于完成目的的心情,没有回收分配的空间)
#include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
using namespace std;
struct node{
int cnt;
node *next[26];
node(){
cnt = 0;
for(int i = 0; i < 26; ++i)
next[i] = NULL;
}
};
char s[2005][22];
void FindPrefix(char *str, int l, node *root){
node *p = root;
for(int i = 0; i < l; ++i){
int t = str[i] - 'a';
p = p->next[t];
printf("%c", str[i]);
if(p->cnt == 1)
return ;
}
return ;
}
int main()
{
node *root = new node;
int tot = 0;
while(scanf("%s", s[tot]) != EOF){
node *p = root;
for(unsigned i = 0; i < strlen(s[tot]); ++i){
int t = s[tot][i] - 'a';
if(p->next[t] == NULL){
p->next[t] = new node;
}
p = p->next[t];
p->cnt++;
}
tot++;
}
for(int i = 0; i < tot; ++i){
printf("%s ", s[i]);
int l = strlen(s[i]);
FindPrefix(s[i], l, root);
printf("\n");
}
return 0;
}