【Phone List 1671 Trie】

来源:互联网 发布:阿里云服务器磁盘挂载 编辑:程序博客网 时间:2024/06/07 22:26

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1671

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct TrieNode{    int count;    struct TrieNode *next[10];};struct TrieNode *root;void Init(){    root=new TrieNode;    root->count=0;    for(int i=0;i<10;i++)        root->next[i]=NULL;}void Insert(char *s){    TrieNode *head=root;    int len=strlen(s);    for(int i=0;i<len;i++){        if(head->next[s[i]-'0']==NULL){            head->next[s[i]-'0']=new TrieNode;            head=head->next[s[i]-'0'];            for(int i=0;i<10;i++)                head->next[i]=NULL;            head->count=1;        }        else{            head=head->next[s[i]-'0'];            head->count++;        }    }}int search(char *s){    TrieNode *head=root;    int len=strlen(s);    for(int i=0;i<len;i++){            head=head->next[s[i]-'0'];    }    return head->count;}void Del(TrieNode *head){    for(int i=0;i<10;i++)        if(head->next[i]!=NULL)            Del(head->next[i]);    free(head);}int main(){    int t,n,i;    char str[10001][20];    scanf("%d",&t);    while(t--){        Init();        scanf("%d",&n);        for(int i=0;i<n;i++){            scanf("%s",str[i]);            Insert(str[i]);        }        int flag=0;        for(int i=0;i<n;i++){            if(search(str[i])!=1){                flag=0;                break;            }            flag=1;        }        if(flag)            printf("YES\n");        else            printf("NO\n");        Del(root);        }}


原创粉丝点击