hdu1671Phone List

来源:互联网 发布:金山软件占市场 编辑:程序博客网 时间:2024/05/18 00:05

普通字典树

建立普通字典树,用flag 标记,注意释放内存空间

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;typedef struct node{    int flag;    struct node *next[10];}Trie;void insertTrie(Trie *root,char *c){    if(root==NULL&&*c=='\0')        return;    Trie *p = root;    while(*c!='\0'){        if(p->next[*c-'0']==NULL){            Trie *q = (Trie*)malloc(sizeof(Trie));            q->flag=0;            for(int i=0;i<10;i++){                q->next[i]=NULL;            }            p->next[*c-'0']=q;            p=p->next[*c-'0'];        }else{            p=p->next[*c-'0'];        }        c++;    }    p->flag=1;}int searchTrie(Trie *root,char *c){    Trie *p = root;    while(*c!='\0'){        if(p->flag==1){//若flag为1则表示有电话号码是其他号码的前缀            return 0;        }else{            if(p->next[*c-'0']!=NULL){                p=p->next[*c-'0'];            }else{                return 0;            }        }        c++;    }    return 1;}void del(Trie *root){//释放内存空间     for(int i=0;i<10;i++){        if(root->next[i]!=NULL)            del(root->next[i]);     }     free(root);}int main(){    int t;    int k;    char phone[10050][15];    int cnt = 0;    int n;    scanf("%d",&t);    while(t--){        Trie *root = (Trie*)malloc(sizeof(Trie));        root->flag=0;        for(int i=0;i<10;i++){            root->next[i]=NULL;        }            cnt=0;        scanf("%d",&n);        while(n--){            scanf("%s",phone[cnt]);            insertTrie(root,phone[cnt]);            cnt++;        }        int i;        for(i=0;i<cnt;i++){            if(searchTrie(root,phone[i])==0){                printf("NO\n");break;            }        }        if(i==cnt)            printf("YES\n");            del(root);    }    return 0;}


0 0
原创粉丝点击