hdu1251 trie樹

本來前幾天就講了的,結果那天走神了,今天才把模板打出來(o(╯□╰)o),順便學了下指針(雖然還是不怎麼懂).

#include <stdio.h>
#include <string,h>
#include <stdlib.h>
typedef struct trie 
{
    int ci; //次數 
    struct trie *net[26];//指針 
}*trienode,Trie; 
trienode root; 
int flag;
char s[15];
void trie_build(char *s)
{
    trienode p=root,ne;
    for (;*s!='\0';s++)
    {
        if (p->net[*s-'a']!=NULL)
        {
            p=p->net[*s-'a'];
            p->ci++;
        } 
        else
        {
            ne=(trienode)malloc(sizeof (Trie));
            for (int i=0;i<26;i++)
            ne->net[i]=NULL;
            ne->ci=1;
            p->net[*s-'a']=ne;
            p=ne;
        }
    } 
} 
int trie_search(char* s)
{
    trienode p=root;
    for (;*s!='\0';s++)
    {
        if (p->net[*s-'a']!=NULL) p=p->net[*s-'a'];
        else return 0;
    }
    return p->ci;
}
void readdata()
{
    root=(trienode)malloc(sizeof(Trie));
    for (int i=0;i<26;i++)
    root->net[i]=NULL;
    root->ci=0;// 初始化 
    flag=0;
    while(gets(s))
    {
        int len=strlen(s); 
        if (len==0) 
        { 
            flag=1;
            continue;
        } 
        if (flag==0) trie_build(s);
        else  printf("%d\n",trie_search(s)); 
    } 
}
int main()
{
    readdata();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章