HDU1251字典樹

來源:互聯網
上載者:User

這題還是一樣的題型,插入和查詢,這次查詢find函數中要注意的就是如果遍曆到一個結點之後對應的next指標為空白,就返回0。

用cnt記錄首碼出現次數,這時候就不用danger標記了。

 

My Code:

#include <vector><br />#include <list><br />#include <map><br />#include <set><br />#include <deque><br />#include <queue><br />#include <algorithm><br />#include <stack><br />#include <bitset><br />#include <functional><br />#include <numeric><br />#include <utility><br />#include <sstream><br />#include <iostream><br />#include <iomanip><br />#include <cstdlib><br />#include <cstdio><br />#include <cstring><br />#include <cctype><br />#include <string><br />#include <ctime><br />#include <cmath><br />using namespace std;<br />const int MAX=1000000;<br />struct Node{<br />int cnt;<br />Node* ne[26];<br />}node[MAX],*root;<br />int K;<br />Node* New(){<br />Node* ret=&node[K++];<br />ret->cnt=0;<br />for(int i=0;i<26;i++){<br />ret->ne[i]=NULL;<br />}</p><p>return ret;<br />}<br />void init(){<br />K=0;<br />root=New();<br />}<br />void insert(char* s){<br />char* p=s;<br />Node* ptr=root;<br />int id;</p><p>while(*p){<br />id=*(p++)-'a';<br />ptr->cnt++;<br />if(ptr->ne[id]==NULL){<br />ptr->ne[id]=New();<br />}<br />ptr=ptr->ne[id];<br />}<br />ptr->cnt++;<br />}<br />int find(char* s){<br />char* p=s;<br />Node* ptr=root;<br />int id;</p><p>while(*p){<br />id=*(p++)-'a';<br />if(ptr->ne[id]==NULL){<br />return 0;<br />}<br />ptr=ptr->ne[id];<br />}</p><p>return ptr->cnt;<br />}<br />int main(){<br />char s[120];</p><p>init();<br />while(gets(s),*s){<br />insert(s);<br />}</p><p>while(gets(s)){<br />printf("%d/n",find(s));<br />}</p><p>return 0;<br />}<br />

 

聯繫我們

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