POJ 3007 Organize Your Train part II(Trie树)

题目链接

注意不要用memset,手写初始化。 直接map TLE,然后哈希字符串同样TLE了。。换了方法终于水过去了。

  1 #include <iostream>

  2 #include <cstdio>

  3 #include <cstring>

  4 #include <cmath>

  5 #include <algorithm>

  6 #include <map>

  7 #include <string>

  8 #include <vector>

  9 using namespace std;

 10 int len;

 11 int trie[100001][26];

 12 int ans,tt;

 13 char s[101];

 14 void cat(char *s1,char *s2,int n)

 15 {

 16     int i,num,z;

 17     num = 0;

 18     for(i = 0; i <= n; i ++)

 19     {

 20         if(!trie[num][s1[i]-'a'])

 21         {

 22             ans ++;

 23             trie[num][s1[i]-'a'] =  ans;

 24             num = ans;

 25         }

 26         else

 27         {

 28             num = trie[num][s1[i]-'a'];

 29         }

 30     }

 31     for(i = n+1; i < len; i ++)

 32     {

 33         if(!trie[num][s2[i-n-1]-'a'])

 34         {

 35             ans ++;

 36             trie[num][s2[i-n-1]-'a'] =  ans;

 37             num = ans;

 38             z = 0;

 39         }

 40         else

 41         {

 42             num = trie[num][s2[i-n-1]-'a'];

 43             z = 1;

 44         }

 45     }

 46     if(z == 0)

 47     {

 48         tt ++;

 49     }

 50 }

 51 int main()

 52 {

 53     int t,i,j,k;

 54     char str[101];

 55     char s1[101],s2[101],s3[101],s4[101];

 56     scanf("%d",&t);

 57     while(t--)

 58     {

 59         for(i = 0;i <= ans;i ++)

 60         {

 61             for(j = 0;j <= 25;j ++)

 62             trie[i][j] = 0;

 63         }

 64         tt = ans = 0;

 65         scanf("%s",str);

 66         len = strlen(str);

 67         if(len == 1)

 68         {

 69             printf("1\n");

 70             continue;

 71         }

 72         for(i = 0; i < len-1; i ++)

 73         {

 74             for(j = 0; j <= i; j ++)

 75             {

 76                 s1[j] = str[j];

 77                 s2[i-j] = str[j];

 78             }

 79             s1[i+1] = '\0';

 80             s2[i+1] = '\0';

 81             for(j = i+1; j < len; j ++)

 82             {

 83                 s3[j-i-1] = str[j];

 84             }

 85             for(j = len-1,k = 0; j >= i+1; j --,k ++)

 86             {

 87                 s4[k] = str[j];

 88             }

 89             s3[len-i-1] = '\0';

 90             s4[len-i-1] = '\0';

 91             cat(s1,s3,i);

 92             cat(s1,s4,i);

 93             cat(s2,s3,i);

 94             cat(s2,s4,i);

 95             cat(s3,s1,len-i-2);

 96             cat(s3,s2,len-i-2);

 97             cat(s4,s1,len-i-2);

 98             cat(s4,s2,len-i-2);

 99         }

100         printf("%d\n",tt);

101     }

102     return 0;

103 }

 

 

你可能感兴趣的:(trie)