码迷,mamicode.com
首页 > 其他好文 > 详细

hdu1247 Hat’s Words

时间:2015-04-23 15:05:37      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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

  1 #include<iostream>
  2 #include<stdio.h>
  3 #include<math.h>
  4 #include<string.h>
  5 #include<stdlib.h>
  6 using namespace std;
  7 char p[50005][30];
  8 struct tree{//建立树
  9     struct tree *next[26];
 10     int n;
 11 }*root;//
 12 
 13 void insert(char *p)//字典树添加
 14 {
 15     struct tree *now,*cur=root;
 16     int len=strlen(p);
 17     for(int i=0;i<len;i++)
 18     {
 19         if(cur->next[p[i]-a]==NULL)//判断字母节点是否存在
 20         {
 21             now=(struct tree*)malloc(sizeof(struct tree));//分配空间
 22             for(int j=0;j<26;j++)
 23             {
 24                 now->next[j]=NULL;//初始化
 25             }
 26             now->n=0;//初始化
 27             cur->next[p[i]-a]=now;
 28             cur=cur->next[p[i]-a];
 29         }
 30         else
 31         {
 32             cur=cur->next[p[i]-a];
 33         }
 34     }
 35     cur->n=1;//字母存在并标记为1
 36 }
 37 
 38 int find2(char *p)//查找后缀树
 39 {
 40     struct tree *cur=root;
 41     for(;*p!=\0;)
 42     {
 43         int d=*p-a;
 44         if(cur->next[d]!=NULL)
 45         {
 46             cur=cur->next[d];
 47             if(cur->n==1 && *(p+1)==\0)//判断条件
 48             return 1;
 49             p++;
 50         }
 51         else
 52         {
 53             return 0;
 54         }
 55     }
 56     return 0;
 57 }
 58 
 59 int find(char *p)//查找
 60 {
 61     struct tree *cur=root;
 62     for(;*p!=\0;)
 63     {
 64         int d=*p-a;
 65         cur=cur->next[d];
 66         if(cur!=NULL)
 67         {
 68             if(cur->n==1 && find2(p+1))//查找前缀字母是否存在,同时判断后缀树
 69             return 1;
 70             p++;
 71         }
 72         else
 73         {
 74             return 0;
 75         }
 76     }
 77     return 0;
 78 }
 79 
 80 int main()
 81 {
 82     //freopen("in.txt","r",stdin);
 83     int i=0;
 84     root=(struct tree*)malloc(sizeof(struct tree));//初始化
 85     for(i=0;i<26;i++)
 86     {
 87         root->next[i]=NULL;
 88     }
 89     root->n=0;
 90     i=0;
 91     while(scanf("%s",p[i])!=EOF)
 92     {
 93         insert(p[i]);
 94         i++;
 95     }
 96     for(int j=0;j<i;j++)
 97     {
 98         int n=find(p[j]);
 99         if(n!=0)
100         printf("%s\n",p[j]);
101     }
102 
103     return 0;
104 }

 

hdu1247 Hat’s Words

标签:

原文地址:http://www.cnblogs.com/xuesen1995/p/4450298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!