题目大意:
输入多串数字串,要求判断是否有的数字串是其它串的前缀。如果存在输出NO,否则输出YES。
解题思路:
用trie建立字典树,然后在每个数字串的结尾处标志1,之后每输入一个串,就判断一下。是否有之前的标志记号。
?
#include
#include
#include
#include
using namespace std; const int MAX_LEN = 11; typedef struct trie { trie *next[10]; int num; }T; T *tree; bool flag; void trieDel(T *p){ for(int i=0;i<10;i++){ if(p->next[i]!=NULL) trieDel(p->next[i]); } free(p); } void trieInsert(char str[]){ T *p=tree,*q; int len=strlen(str); for(int i=0;i
next[id]==NULL){ q=new T; for(int j=0;j<10;j++) q->next[j]=NULL; q->num=0; p->next[id]=q; p=p->next[id]; } else p=p->next[id]; if(p->num == 1) flag =false; } p->num=1; for(int i=0;i<10;i++){ if(p->next[i]!=NULL){ flag=false; break; } } } void init(){ tree = new T; for(int i=0;i<10;i++) { tree->next[i]=NULL; } } int main() { int cas; scanf("%d",&cas); while(cas--){ flag=true; int n; scanf("%d",&n); getchar(); init(); for(int i=0;i
以下代码没用字典树:
?
?
#include
#include
#include