zoukankan      html  css  js  c++  java
  • hdu 1247 Hat’s Words(Trie树)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1247

    View Code
     1 #include <iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 using namespace std;
     5 char str[50010][105];
     6 struct node
     7 {
     8     int flag;
     9     node *next[26];
    10 };
    11 node *build()
    12 {
    13     int i;
    14     node *p;
    15     p=new node;
    16     p->flag=0;
    17     for(i=0;i<26;i++)
    18     p->next[i]=NULL;
    19     return p;
    20 }
    21 void insert(node *p,char *s)
    22 {
    23     int len,i,t;
    24     len=strlen(s);
    25     for(i=0;i<len;i++)
    26     {
    27         t=s[i]-'a';
    28         if(p->next[t]==NULL)
    29         p->next[t]=build();
    30         p=p->next[t];
    31     }
    32     p->flag=1;
    33 }
    34 int sear(node *p,char *s)                //这样写就wa了,不明白为什么。。。
    35 {                                       //{
    36     int t;                              //  int t;   
    37     while(*s!='\0')                     //  while(*s!='\0')
    38     {                                   //  {
    39         t=*s-'a';                       //      t=*s-'a';
    40         if(p->next[t]==NULL)            //      if(p->next[t]=NULL)
    41         return 0;                       //        return 0;
    42         p=p->next[t];                   //      p=p->next[t];
    43          if(p->flag==1&&*(s+1)=='\0')   //      s++;
    44         return 1;                       //  }
    45         s++;                            //  if(p->flag==1)
    46     }                                   //  return 1;
    47     return 0;                           //  return 0;
    48 }                                       //}
    49 int search(node *p,char *s)
    50 {                                      
    51     int len,i,t;                        
    52     node *h;                           
    53     h=p;                               
    54     len=strlen(s);
    55     for(i=0;i<len;i++)
    56     {
    57         t=s[i]-'a';
    58         if(h->next[t]==NULL)
    59         return 0;
    60         h=h->next[t];
    61         if(h->flag==1&&sear(p,s+i+1))
    62         return 1;
    63     }
    64     return 0;
    65 }
    66 int main()
    67 {
    68     int i=0,j;
    69     node *p;
    70     p=build();
    71     while(gets(str[i])!=NULL)
    72     {
    73         insert(p,str[i]);
    74         i++;
    75     }
    76     for(j=0;j<i;j++)
    77     {
    78         if(search(p,str[j]))
    79         puts(str[j]);
    80     }
    81     return 0;
    82 }
  • 相关阅读:
    页面引入js问题
    python之循环语句与注释
    python之字符串格式化方法
    python之对象的方法
    python之函数
    python之条件判断
    python之布尔表达式
    python之列表与元组
    python之字符串
    搞不明白的recycling process 和 finalization process
  • 原文地址:https://www.cnblogs.com/wanglin2011/p/2636966.html
Copyright © 2011-2022 走看看