POJ 3080 Blue Jeans(KMP)

题目链接

kmp专题剩下的题,没看清题目要求字典序最小,开始加了最优的剪枝,长度相同的时候直接continue了,导致再去改字典序的时候没改这句话,错了几次。

又到了放假切题的时候了。。

 1 #include <cstdio>

 2 #include <cmath>

 3 #include <cstring>

 4 using namespace std;

 5 char s[11][101];

 6 int next[301];

 7 int kmp(int L,int R,int x)

 8 {

 9     int i,j,len1,len2;

10     char str[101];

11     for(i = L,j = 0;i <= R;i ++,j ++)

12     str[j] = s[1][i];

13     len1 = j;

14     next[0] = -1;

15     j = -1;

16     for(i = 1;i <= len1-1;i ++)

17     {

18         while(j >= 0&&str[j] != str[i])

19         j = next[j];

20         if(str[j+1] == str[i])j ++;

21         next[i] = j;

22     }

23     len2 = strlen(s[x]);

24     j = -1;

25     for(i = 0;i <= len2-1;i ++)

26     {

27         while(j >= 0&&str[j+1] != s[x][i])

28         j = next[j];

29         if(str[j+1] == s[x][i]) j ++;

30         if(j == len1-1)

31         return 1;

32     }

33     return 0;

34 }

35 int main()

36 {

37     int t,m,i,j,k,len,ans,u;

38     char o[101];

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

40     while(t--)

41     {

42         scanf("%d",&m);

43         for(i = 1;i <= m;i ++)

44         scanf("%s",s[i]);

45         len = strlen(s[1]);

46         ans = 0;

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

48         {

49             for(j = i+2;j <= len-1;j ++)

50             {

51                 for(k = 2;k <= m;k ++)

52                 {

53                     if(!kmp(i,j,k))

54                     break;

55                 }

56                 if(k == m+1&&ans < j-i+1)

57                 {

58                     ans = j-i+1;

59                     for(u = 0;u <= j-i;u ++)

60                     o[u] = s[1][u+i];

61                     o[u] = '\0';

62                 }

63                 else if(k == m+1&&ans == j-i+1)

64                 {

65                     int z = 1;

66                     for(u = 0;u <= j-i;u ++)

67                     {

68                         if(o[u] < s[1][u+i])

69                         {

70                             z = 1;

71                             break;

72                         }

73                         else if(o[u] > s[1][u+i])

74                         {

75                             z = 0;

76                             break;

77                         }

78                     }

79                     if(!z)

80                     {

81                         for(u = 0;u <= j-i;u ++)

82                         o[u] = s[1][u+i];

83                         o[u] = '\0';

84                     }

85                 }

86             }

87         }

88         if(ans == 0)

89         printf("no significant commonalities\n");

90         else

91         {

92             printf("%s\n",o);

93         }

94     }

95     return 0;

96 }

 

你可能感兴趣的:(poj)