HDU1247字典樹

來源:互聯網
上載者:User

本題思路和一般字典樹有所不同,將全部的字串讀入離線處理,insert操作和大部分字典樹一致,接下來就是一個dfs函數,枚舉全部字串是否是合格,dfs的tim參數表示了這個是第幾次查詢,如果遇到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 />Node* ne[26];<br />bool danger;<br />}node[MAX],*root;<br />char in[50010][50];<br />int K;<br />Node* New(){<br />Node* ret=&node[K++];<br />for(int i=0;i<26;i++){<br />ret->ne[i]=NULL;<br />}<br />ret->danger=false;</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 />if(ptr->ne[id]==NULL){<br />ptr->ne[id]=New();<br />}<br />ptr=ptr->ne[id];<br />}</p><p>ptr->danger=true;<br />}<br />bool dfs(char* s,int tim){<br />//tim=0 means that it is the first time search,<br />//otherwise it is the second time.<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 false;//if the next pointer is null, return false.<br />}<br />ptr=ptr->ne[id];<br />//important.<br />//if this node is a danger case, we search a second time.<br />if(ptr->danger){<br />if(tim==0&&*p&&dfs(p,1)){<br />return true;<br />}<br />}<br />}</p><p>//if the node is dangerous and the string has been completely search<br />//return true.<br />if(tim==1&&ptr->danger){<br />return true;<br />}else{<br />return false;<br />}<br />}<br />int main(){<br />int n=0;</p><p>init();<br />while(gets(in[n])){<br />insert(in[n]);<br />n++;<br />}</p><p>for(int i=0;i<n;i++){<br />if(dfs(in[i],0)){<br />puts(in[i]);<br />}<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.