phone list (dictionary tree)

#include<iostream>
#include<cstring>
using namespace std;
struct node{int son[11];//The phone number is up to 11 digits
bool ed;
void clear(){
memset(son,0,sizeof(son));
ed=0;
}
};
node tree[100010];
char s[10010][11];
int tot;
void insert(int k){
int l = strlen(s[k]), p = 1;
for (int i = 0; i < l; i++) {
if(tree[p].son[s[k][i]-'0']==0)tree[p].son[s[k][i] -'0']=++tot;//(Numbers 0-9 characters, subtract the ascii code of 0 from their ascii code, which is convenient for storage)

(If the result is 0, it means that it has not been entered yet, insert it at the new node)

p= tree[p].son[s[k][i]-'0'];//指针移动到下一个节点
}
tree[p].ed=1;//输入就标记
}
bool check(int k) {
int l =strlen(s[k]),p=1;
for(int i=0;i<l;i++){
if(tree[p].son[s[k][i]-'0']==0)return 0;
if(tree[p].ed)return 1;
p=tree[p].son[s[k][i]-'0'];
}
return 0;
}
int main(){
int N;
cin>>N;
for(int j=0;j<N;j++){
for(int i=1;i<=100010;i++)if(tree[i].ed)tree[i].clear();
tot=1;
int n;bool f=0;
cin>>n;
for(int i=1;i<=n;i++){
scanf("%s",s[i]);
insert(i);
}
for(int i=1;i<=n;i++){
if(check(i)){
f=1;break;
}
}
if(f)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}

(refer to http://www.cnblogs.com/luyouqi233/p/7859297.html, thanks for the code shared by this blogger)

(When the pointer is used to write the structure, the operation will flash back directly, and the reason will be found and posted)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324973812&siteId=291194637