Shortest Prefixes 字典树模板

题意

  给你一堆字符串,要求找到每个字符串的唯一标识前缀,输出原字符串和唯一标识前缀。

思路

  用这堆字符串建字典树,对于每个字符串,我们进行一次查找,若当前位置的cnt为1,就代表从根到现在的位置能唯一标识。

AC代码

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=1e3+5;
int t,n;
char str[maxn][25];
struct node{
    int cnt;
    struct node *next[26];
    node(){
        cnt=0;
        memset(next,0,sizeof(next));
    }
};
node *root;
void buildtrie(char *s){
    node *p=root;
    node *tmp=NULL;
    int len=strlen(s);
    for(int i=0;i<len;i++){
        if(p->next[s[i]-'a']==NULL){
            tmp=new node;
            p->next[s[i]-'a']=tmp;
        }
        p=p->next[s[i]-'a'];
        p->cnt++;
    }
}
void findtrie(char *s){
    node *p=root;
    int len=strlen(s);
    for(int i=0;i<len;i++){     
        p=p->next[s[i]-'a'];
        printf("%c",s[i]);
        if(p->cnt==1){
            return;
        }
    }    
}
void del(node *root){
    for(int i=0;i<26;i++){
        if(root->next[i])
            del(root->next[i]);
    }
    delete(root);
}
int main()
{
    root=new node;
    int k=0;
    while(~scanf("%s",&str[k])){
        buildtrie(str[k]);
        k++;
    }
    for(int i=0;i<k;i++){
        printf("%s ",str[i]);
        findtrie(str[i]);
        printf("\n");
    }
    return 0;
}

 

posted @ 2020-07-29 11:16  艾尔夏尔-Layton  阅读(93)  评论(0编辑  收藏  举报