HDU 1247 Hat’s Words(Tire树)

题目链接

我那个纠结啊。。。。看了大半天终于,把tire树敲出来,数组开小RE了N次,还死活以为是指针越界别的什么的。。。没看开始字符数组开小了。。无语啊。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <stdlib.h>

 4 char word[50001][101];

 5 struct node

 6 {

 7     int flag;

 8     struct node *next[26];

 9 };

10 struct node *build()

11 {

12     int i;

13     struct node *p;

14     p = (struct node *)malloc(sizeof(struct node));

15     p -> flag = 0;

16     for(i = 0;i <= 25;i ++)

17     p -> next[i] = NULL;

18     return p;

19 }

20 void insert(struct node *head,char *str)

21 {

22     int i;

23     struct node *p;

24     p = head;

25     for(i = 0;str[i];i ++)

26     {

27         if(p -> next[str[i]-'a'] == NULL)

28         {

29             p -> next[str[i]-'a'] = build();

30         }

31         p = p -> next[str[i]-'a'];

32     }

33     p -> flag = 1;

34 }

35 int judge(struct node *head,char *str)

36 {

37     int i;

38     struct node *p;

39     p = head;

40     for(i = 0;str[i];i ++)

41     {

42         if(p -> next[str[i]-'a'] == NULL)

43         return 0;

44         p = p -> next[str[i]-'a'];

45         if(p -> flag&&str[i+1] == '\0')

46         return 1;

47     }

48     return 0;

49 }

50 int search(struct node *head,char *str)

51 {

52     int i;

53     struct node *p;

54     p = head;

55     for(i = 0;str[i];i ++)

56     {

57         if(p -> next[str[i]-'a'] == NULL)

58         return 0;

59         p = p -> next[str[i]-'a'];

60         if(str[i+1] != '\0')

61         {

62             if(p ->flag&&judge(head,str+i+1))

63             return 1;

64         }

65     }

66     return 0;

67 }

68 int main()

69 {

70     int i,j;

71     struct node *head;

72     i = 1;

73     head = build();

74     while(scanf("%s",word[i])!=EOF)

75     {

76         insert(head,word[i]);

77         i ++;

78     }

79     for(j = 1;j <= i-1;j ++)

80     {

81         if(search(head,word[j]))

82         printf("%s\n",word[j]);

83     }

84     return 0;

85 }

你可能感兴趣的:(word)