Sicily 1426 Phone List(Trie树)

//Trie树 //对每个号码构造Trie树,利用状态status进行识别 #include<iostream> #include<cstring> using namespace std; struct Node { Node *num[10]; int status;//status = 1表示前面已有电话号码经过该结点,2表示电话号码在该结点结束 Node() { for(int i = 0 ;i < 10;++i) num[i] = NULL; status = 0; } }*root; bool Trie(char phoneNum[],Node *p) { int end = strlen(phoneNum); for(int i = 0;i < end;++i) { if(p->num[phoneNum[i] - '0']) { p = p->num[phoneNum[i] - '0']; if(p->status == 2) return false; if(p->status == 1 && i == end - 1) return false; } else { p->num[phoneNum[i] - '0'] = new Node; p = p->num[phoneNum[i] - '0']; if(i == end - 1) { p->status = 2; } else p->status = 1; } } return true; } void release(Node *p)//释放空间 { for(int i = 0;i < 10;++i) if(p->num[i]) release(p->num[i]); delete p; } int main() { //freopen("in.txt","r",stdin); int t,n,res; char phoneNum[15]; scanf("%d",&t); while(t--) { res = 1; root = new Node; scanf("%d",&n); for(int i = 0;i < n;++i) { scanf("%s",phoneNum); if(Trie(phoneNum,root)) continue; else res = 0; } if(res) printf("YES/n"); else printf("NO/n"); release(root); } return 0; } 

你可能感兴趣的:(list,delete,电话)