zoukankan      html  css  js  c++  java
  • 字典树trie

    字典树trie

    又称单词查找树,trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。(这段来自百度百科。。)

    字典树

    char word1[maxn][51],word2[maxn][51];
    int cnt=0;
    char ans[51];
    
    struct Node
    {
        char s[51];
        bool end;      //结束标志,1表示有单词,0表示没有
        Node *next[26];
    };Node T={{0},0,{NULL}}; //头结点不存数据,牺牲一个结点的空间只是为了方便。。
    
    void insert(char*s1,char*s2)
    {
        Node *p=&T;
        for(int i=0;i<strlen(s2);i++){
            if(p->next[s2[i]-'a']==NULL){
                Node *newnode=(Node*)malloc(sizeof(Node));
                memset(newnode,0,sizeof(Node));
                p->next[s2[i]-'a']=newnode;
            }
            p=p->next[s2[i]-'a'];
        }
        p->end=1;
        strcpy(p->s,s1);
    }
    
    bool find(char *s)
    {
        Node *p=&T;
        for(int i=0;i<strlen(s);i++){
            if(p->next[s[i]-'a']==NULL) return false;
            p=p->next[s[i]-'a'];
        }
        if(p->end==0) return false;
        strcpy(ans,p->s);
        return true;
    }
    
    int main()
    {
        char tmp[110];
        while(gets(tmp)&&strlen(tmp)){
            sscanf(tmp,"%s%s",word1[cnt],word2[cnt]);
            insert(word1[cnt],word2[cnt]);
            cnt++;
        }
        while(gets(tmp)!=NULL&&strlen(tmp)){
            if(find(tmp)) printf("%s
    ",ans);
            else printf("eh
    ");
        }
        return 0;
    }
    trie树
    没有AC不了的题,只有不努力的ACMER!
  • 相关阅读:
    洛谷 P1194 飞扬的小鸟 题解
    洛谷 P1197 星球大战 题解
    洛谷 P1879 玉米田Corn Fields 题解
    洛谷 P2796 Facer的程序 题解
    洛谷 P2398 GCD SUM 题解
    洛谷 P2051 中国象棋 题解
    洛谷 P1472 奶牛家谱 Cow Pedigrees 题解
    洛谷 P1004 方格取数 题解
    洛谷 P2331 最大子矩阵 题解
    洛谷 P1073 最优贸易 题解
  • 原文地址:https://www.cnblogs.com/--560/p/4330230.html
Copyright © 2011-2022 走看看