hdu 1251 統計難題 (字典樹)

來源:互聯網
上載者:User
統計難題

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)

Total Submission(s): 13884    Accepted Submission(s): 5971Problem DescriptionIgnatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為首碼的單詞數量(單詞本身也是自己的首碼). 

Input輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串.

注意:本題只有一組測試資料,處理到檔案結束. 

Output對於每個提問,給出以該字串為首碼的單詞的數量. 

Sample Input

bananabandbeeabsoluteacmbabbandabc
 

Sample Output

2310
 思路:字典樹。
代碼:
#include <iostream>#include <cstdlib>#include <cstdio>#include <cstring>#define MAX 26using namespace std;int n,m;char ss[1005];struct Trie                  //Trie結點聲明{    int isStr;               //記錄該結點處有多少單詞經過    Trie *next[MAX];         //兒子分支};void insert(Trie *root,const char*s)    //將單詞s插入到字典樹中{    if(root==NULL||*s=='\0') return;    int i;    Trie *p=root;    while(*s!='\0')    {        if(p->next[*s-'a']==NULL)       //如果不存在,則建立結點        {            Trie *temp=(Trie *)malloc(sizeof(Trie));            for(i=0; i<MAX; i++)            {                temp->next[i]=NULL;            }            temp->isStr=1;            p->next[*s-'a']=temp;            p=p->next[*s-'a'];        }        else        {            p=p->next[*s-'a'];            p->isStr++;        }        s++;    }}int search(Trie *root,const char*s){    Trie *p=root;    while(p!=NULL&&*s!='\0')    {        p=p->next[*s-'a'];        s++;    }    if(p!=NULL)  return p->isStr;    return 0;}void del(Trie *root)                     //釋放整個字典樹占的堆區空間{    int i;    for(i=0; i<MAX; i++)    {        if(root->next[i]!=NULL)        {            del(root->next[i]);        }    }    free(root);}int main(){    int i;    Trie *root= (Trie *)malloc(sizeof(Trie));    for(i=0; i<MAX; i++)    {        root->next[i]=NULL;    }    root->isStr=0;    while(1)    {        gets(ss);        if(strlen(ss)==0||ss[0]==' ') break ;        insert(root,ss);    }    while(gets(ss)!=NULL)    {        printf("%d\n",search(root,ss));    }    del(root);                        //釋放空間很重要    return 0;}/*allocallalloalalall*/
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.