标签:
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12684 Accepted Submission(s): 4307
/** 题意:给出n个电话号码,要求是否存在有的号码是另外一个字符串的前缀 做法:Trie树 一直是RE 是把主函数的root = new node() 写成 p = new node() 然后 C++MLE 然后每次询问完删除树就OK **/ #include <iostream> #include <stdio.h> #include <algorithm> #include <string.h> #include <cmath> using namespace std; char ch[10005][12]; struct node { int count; node *next[10]; node() { count = 0; for(int i=0;i<10;i++) { next[i] = NULL; } } }; node *root = new node(),*p; void insert(char *s) { p = root; for(int i=0;i<strlen(s);i++) { int tt = s[i] -‘0‘; if(p->next[tt] == NULL) p->next[tt] = new node(); p = p->next[tt]; p->count++; } } int find(char *c) { int i; p = root; int len = strlen(c); for(i=0;i<len;i++) { int tt = c[i]-‘0‘; if(p->next[tt]->count== 1) break; p = p->next[tt]; } if(i == len) return 0; else return 1; } void freedom(node *pp) { for(int i=0;i<10;i++) { if(pp->next[i] != NULL) freedom(pp->next[i]); } free(pp); } int main() { // freopen("in.txt","r",stdin); int T; scanf("%d",&T); while(T--) { root = new node(); int n; bool flag = true; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%s",ch[i]); insert(ch[i]); } for(int i=0;i<n;i++) { if(find(ch[i]) == 0) { flag = false; break; } } if(!flag) printf("NO\n"); else printf("YES\n"); freedom(root); } return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/4589805.html