HDU 1251 統計難題 (字典樹基本模板,有詳細注釋)

來源:互聯網
上載者:User

連結:http://acm.hdu.edu.cn/showproblem.php?pid=1251

 

題目的意思已經很明白了:統計出以某個字串為首碼的單詞數量(單詞本身也是自己的首碼).

我這就直接給字典樹基礎模板了,給了一些注釋,望各位能理解

 

#include <iostream>#include <cstring>using namespace std;typedef struct tree //建立節點{    int num;    struct tree *br[26]; //每一層有26個字母}Node;Node *head;void Tree_Insert(char str[])//建樹{    Node *t,*s=head;    int i,j;    int len=strlen(str);    for(i=0;i<len;i++)    {        int id=str[i]-'a';         if(s->br[id]==NULL)         {            t=new Node; //在這個字母下面在開闢新的結點            for(j=0;j<=25;j++)//初始化新結點    {                t->br[j] = NULL;            }            t->num=0;            s->br[id]=t;  //標記這個結點連結的子樹指標        }        s=s->br[id]; //s指向下一個結點        s->num ++;  //經過這個點的次數    }}int Tree_Find(char str[]) //搜尋過程,從每位字母開始搜{    Node *s = head;    int count;    int len=strlen(str);    for(int i=0;i<len;i++){        int Id=str[i]-'a';        if(s->br[Id]==NULL)        {            count=0;            return count ;        }        else{            s=s->br[Id];            count=s->num;        }            }    return count;}int main(){    int i;    head=new Node; //頭結點    for(i=0;i<=25;i++)//26個結點,初始化    {        head->br[i]=NULL;         head->num=0;    }    char tem[15];    while(gets(tem),strcmp(tem,""))   {        Tree_Insert(tem);  //建樹    }    while(gets(tem)){        cout<<Tree_Find(tem)<<endl;    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.