zoukankan      html  css  js  c++  java
  • HDU 1251 统计难题(字典树计算前缀数量)

      字典树应用,每个节点上对应的cnt是以它为前缀的单词的数量

    #include<stdio.h>
    #include<string.h>
    struct trie
    {
        int cnt;
        trie *next[26];
    };
    trie *root=new trie;
    void insert(char ch[])
    {
        trie *p=root,*newnode;
        for(int i=0; ch[i]!=''; i++)
        {
            if(p->next[ch[i]-'a']==0)
            {
                newnode=new trie;
                for(int j=0; j!=26; j++)
                {
                    newnode->next[j]=NULL;
                }
                newnode->cnt=1;
                p->next[ch[i]-'a']=newnode;
                p=newnode;
            }
            else
            {
                p=p->next[ch[i]-'a'];
                p->cnt++;
            }
        }
    }
    int find(char ch[])
    {
        trie *p=root;
        for(int i=0; ch[i]!=''; i++)
        {
            if(p->next[ch[i]-'a']!=NULL)
                p=p->next[ch[i]-'a'];
            else
                return 0;
        }
        return p->cnt;
    }
    int main()
    {
        char ch[20];
        for(int i=0; i!=26; i++)
        {
            root->next[i]=NULL;
        }
        root->cnt=0;
        while(gets(ch)) //±ØÐëÓÃgets
        {
            if(!strcmp(ch,"")) break;
            insert(ch);
        }
        while(scanf("%s",ch)!=EOF)
        {
            printf("%d
    ",find(ch));
        }
        return 0;
    }
  • 相关阅读:
    CADisplayLink
    对项目重命名
    TCP|UDP|Http|Socket
    CoreAnimation|动画
    Autolayout
    通讯录
    本地通知
    用于做 Android 屏幕自适应的文章资源
    Java String.format 自动补全不够的位数
    不同语言之间 日期格式转换
  • 原文地址:https://www.cnblogs.com/jifahu/p/5449340.html
Copyright © 2011-2022 走看看