ZOJ-1875-Phone List-字典树

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1875

 

思路:字典树判断前缀,插入号码的时候就开始判断,一旦出现重复前缀,之后的号码就不进行插入操作(经过实践,实践实践相差10ms而已)

这题只要拿字典树的模板,然后稍加修改就能AC,另外再加上del(root)释放一下

#include "cstdlib" #include "cctype" #include "cstring" #include "cstdio" #include "cmath" #include "algorithm" #include "vector" #include "string" #include "iostream" #include "sstream" #include "set" #include "queue" #include "stack" #include "fstream" #include "iomanip" #include "bitset" #include "list" #include "ctime" using namespace std; struct Trie{ Trie *child[10]; int data, flag; Trie(){ for(int i = 0; i < 10; i++) child[i] = NULL; flag = data = 0; } }; bool insert(Trie *&root, char *s){ int i, idx; Trie *cur = root; if(cur == NULL){ cur = new Trie(); root = cur; } for(i = 0; s[i]; i++){ idx = s[i] - '0'; if(cur->child[idx] == NULL){ cur->child[idx] = new Trie(); } cur = cur->child[idx]; if(cur->flag) return false; cur->data++; } cur->flag = 1; if(cur->data > 1) return false; return true; } void del(Trie *root){ if(root){ for(int i = 0; i < 10; i++){ del(root->child[i]); } delete(root); } } int main(){ int t, n, i, ans; char num[20]; scanf("%d",&t); Trie *root; while(t--){ root = NULL; scanf("%d",&n); ans = 1; for(i = 0; i < n; i++){ scanf("%s",num); if(!insert(root, num)){ ans = 0; i++; break; } } for(; i < n; i++) scanf("%s",num); if(ans) puts("YES"); else puts("NO"); del(root); } return 0; }

 

 

你可能感兴趣的:(ZOJ-1875-Phone List-字典树)