zoukankan      html  css  js  c++  java
  • 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("
    ");
        }
        return 0;
    }
  • 相关阅读:
    JetBrains下载历史版本
    php入门笔记
    Ajax获取服务器信息
    Ubuntu上安装PHP环境-mysql+apache+php-Linux操作系统
    Ubuntu彻底删除/卸载mysql,php,apache
    轻松理解JS基本包装对象
    JS事件委托
    浅谈JS事件冒泡
    JS闭包那些事
    浅谈JS的变量提升
  • 原文地址:https://www.cnblogs.com/qq2210446939/p/13396009.html
Copyright © 2011-2022 走看看