這題糾結了好久,之前沒有考慮到flag標記,如果有如下的資料,之前的想法就錯了:
1
2
00000
000
直接建字典樹,注意一下幾點:
1.如果當前的結點是標記了danger的,那麼就直接返回false,表示有首碼。
2.如果遍曆到最後依然沒有發現danger標記,要考慮這個結點有沒有後繼,如果有,說明他是某些結點的首碼,這個用flag標記。
自己在代碼裡加了一些注釋,以便理解。
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[10];<br />bool danger,flag;//if node has next pointer set the flag true<br />}node[MAX],*root;<br />int K;<br />Node* New(){<br />//get a new pointer which has not be allocate.<br />Node* ret=&node[K++];<br />for(int i=0;i<10;i++){<br />ret->ne[i]=NULL;<br />}<br />ret->danger=false;<br />ret->flag=false;<br />return ret;<br />}<br />void init(){<br />K=0;<br />root=New();<br />}<br />bool insert(char* s){<br />Node* ptr=root;<br />char* p=s;<br />int id;</p><p>//go along the tree and find whether<br />//s has a dangerous prefix.<br />while(*p){<br />id=*(p++)-'0';<br />if(ptr->danger){<br />return false;<br />}<br />if(ptr->ne[id]==NULL){<br />ptr->ne[id]=New();<br />}<br />ptr->flag=true;//set the flag true because this node has next pointer.<br />ptr=ptr->ne[id];<br />}<br />ptr->danger=true;<br />//notice: if the next pointer is not null<br />//we say s is a prefix of some words.<br />if(ptr->flag){<br />return false;<br />}</p><p>return true;<br />}<br />int main(){<br />int t;<br />int n;<br />bool done;<br />char s[1100];</p><p>scanf("%d",&t);<br />while(t--){<br />init();<br />scanf("%d",&n);<br />done=true;<br />for(int i=0;i<n;i++){<br />scanf("%s",s);<br />if(done){<br />done=insert(s);<br />}<br />}<br />if(done){<br />puts("YES");<br />}else{<br />puts("NO");<br />}<br />}</p><p>return 0;<br />}<br />