這題還是一樣的題型,插入和查詢,這次查詢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 />