HDU 1671(Phone List)
题目链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1671
动态分配内存,当实例较多时需释放内存,不然会超空间
#include<iostream> #include<string> #include<cstdio> using namespace std; #define maxn 10001 char s[maxn][11]; struct Trie { Trie *next[10]; Trie() { memset(next,0,sizeof(next)); } }; void Insert(Trie *root,char s[]) { Trie *p = root; for(int i = 0; i < strlen(s); i++) { int j = s[i] - '0'; if(p->next[j] == NULL) p->next[j] = new Trie(); p = p->next[j]; } } bool Find(Trie *root,char s[]) { Trie *p = root; for(int i = 0; i < strlen(s); i++) { int j = s[i] - '0'; if(p->next[j] == NULL) return false; p = p->next[j]; } for(int k = 0 ;k < 10; k++) if(p->next[k] != NULL) return true; return false; } void Delete(Trie *root) //释放内存 { for(int i=0;i<10;i++) { if(root->next[i]!=NULL) Delete(root->next[i]); delete root->next[i]; root->next[i]=NULL; } } int main() { //freopen("1005.txt","r",stdin); int i,t,n; cin >> t; while(t--) { Trie *root = new Trie(); cin >> n; for(i = 0; i < n; i++) { scanf("%s",s[i]); Insert(root,s[i]); } for(i = 0; i < n; i++) if(Find(root,s[i])) { cout << "NO" << endl; break; } if(i == n) cout << "YES" << endl; Delete(root); } return 0; }

浙公网安备 33010602011771号