标签:trie
题意:判断是否有某字符串是别的字符串的前缀。是则输出NO,不然输出YES。
思路:把板子写成结构体版的。。详见代码:
/********************************************************* file name: poj3630.cpp author : kereo create time: 2015年02月09日 星期一 22时22分45秒 *********************************************************/ #include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<set> #include<map> #include<vector> #include<stack> #include<cmath> #include<string> #include<algorithm> using namespace std; typedef long long ll; const int sigma_size=26; const int N=100+50; const int MAXN=100000+50; const int inf=0x3fffffff; const double eps=1e-8; const int mod=1000000000+7; #define L(x) (x<<1) #define R(x) (x<<1|1) #define PII pair<int, int> #define mk(x,y) make_pair((x),(y)) int n,sz,flag; char str[N]; struct node{ int id,val; node *ch[sigma_size]; }nod[MAXN],*root,*null,nil; struct Trie{ void init(){ sz=0; nil.id=0; null=&nil; newnode(root); } void newnode(node *&x){ x=&nod[sz]; x->val=0; x->id=sz++; for(int i=0;i<sigma_size;i++) x->ch[i]=null; } void insert(char *str){ int len=strlen(str); node *p=root; for(int i=0;i<len;i++){ int k=str[i]-'0'; if(p->ch[k] == null) newnode(p->ch[k]); if(p->val) flag=1; p=p->ch[k]; } p->val=1; for(int i=0;i<sigma_size;i++) if(p->ch[i]!=null){ flag=1; break; } } }trie; int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); trie.init(); flag=0; for(int i=0;i<n;i++){ scanf("%s",str); trie.insert(str); } if(flag) printf("NO\n"); else printf("YES\n"); } return 0; }
标签:trie
原文地址:http://blog.csdn.net/u011645923/article/details/43680023