本題思路和一般字典樹有所不同,將全部的字串讀入離線處理,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 />