字典樹(Tire)模板

來源:互聯網
上載者:User

標籤:

 1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 struct node 5 { 6     node *ne[26]; 7     int cnt; 8 }*head; 9 void insert(char *s)10 {11     node *p=head,*q;12     for(int i=0;s[i];i++)13     {14         int id=s[i]-‘a‘;15         if(p->ne[id]!=NULL)16         {17             p=p->ne[id];18             p->cnt++;19         }20         else21         {22             q=(node*)malloc(sizeof(node));23             for(int i=0;i<26;i++)24                 q->ne[i]=NULL;25             q->cnt=1;26             p->ne[id]=q;27             p=p->ne[id];28         }29     }30 }31 int Q(char *s)//查詢有多少以該串為首碼的串的數量32 {33     node *p=head;34     for(int i=0;s[i];i++)35     {36         int id=s[i]-‘a‘;37         if(p->ne[id]!=NULL)38             p=p->ne[id];39         else40             return 0;41     }42     return p->cnt;43 }44 void clean(node *p)//釋放空間45 {46     if(p==NULL)    return ;47     for(int i=0;i<26;i++)48     {49         if(p->ne[i]!=NULL)50             clean(p->ne[i]);51     }52     free(p);53     return ;54 }55 int main()56 {57     int n,m;58     char s[11];59     while(scanf("%d",&n)!=EOF)60     {61         head=(node*)malloc(sizeof(node));62         for(int i=0;i<26;i++)63             head->ne[i]=NULL;64         while(n--)65         {66             scanf("%s",s);67             insert(s);68         }69         scanf("%d",&m);70         while(m--)71         {72             scanf("%s",s);73             printf("%d\n",Q(s));74         }75         clean(head);76     }77     return 0;78 }

 

字典樹(Tire)模板

聯繫我們

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