poj 3630 Phone List

来源:互联网 发布:咸鱼表情出处 知乎 编辑:程序博客网 时间:2024/05/25 21:32

   开始学字典树了,以前看过AC自动机,但现在感觉和没学一样的感觉,不过字典树还是挺好理解的,不懂的点击打开链接,这题算是字典树的入门题吧,但是需要注意判断的情况,可能别人是它的前缀,或者他是别人的前缀。

 

#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int N = 100000;struct Node {bool flag;Node *next[10];}root;Node node[N];int tot;bool insert(char *str){     Node *p = &root;     bool ff = false;     while(*str)     {       if(p->flag)        return true;       if(p->next[*str - '0'] == NULL)       {         ff = true;         node[tot].flag = false;         memset(node[tot].next, NULL, sizeof(node[tot].next));         p->next[*str - '0'] = &node[tot++];       }       p = p->next[*str - '0'];       str++;     }     p->flag = true;     if(!ff)     return true;     else     return false;}int main(void){    int ncase;    cin >> ncase;    while(ncase --)    {      int n;      memset(root.next, NULL, sizeof(root.next));      cin >> n;      bool flag = false;      tot = 0;      char str1[20];      while(n--)      {        scanf("%s",str1);        if(!flag)        {            flag = insert(str1);        }      }      if(!flag)        cout<<"YES"<<endl;      else        cout<<"NO"<<endl;    }    return 0;}


原创粉丝点击