Xtreme9.0 - Pattern 3 KMP

Pattern 3

题目连接:

https://www.hackerrank.com/contests/ieeextreme-challenges/challenges/car-spark

Description

Vangelis the bear received a digital signal pattern generator that his brother Mitsos built. The generator produces a signal that is encoded using the Latin alphabet. Vangelis starts the generator for some time and records the signal generated. He wants to study the sample he received and try to identify the smallest pattern that the generator could be using to generate the sample.

Your task is to help Vangelis by writing a program that will calculate the length of the smallest valid pattern.

Input

The input is made up of multiple test cases.

The first line contains an integer T (1 <= T <= 10), the number of test cases in this file.

Each line contains an encoded signal. The signal is encoded using the small letters of the Latin alphabet. The length of a signal is between 1 and 106 characters, inclusive.

Vangelis has started the recording at the beginning of a pattern, so each line begins with the first character in the pattern. His recording lasts for at least one pattern length, but the length of the recording may not be an exact multiple of the pattern length.

Output

There must be T lines of output and each line will contain a single non-negative integer number, the length of the minimum valid pattern.

Sample Input

6
abab
abababababababababab
abababababab
abc
aaaaaa
aabaabbaabaabbaabaabbaabaab

Sample Output

2
2
2
3
1
7

Hint

题意

求最小循环节的大小

题解

KMP裸题

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+7;
char s[maxn];
int p[maxn];
int main()
{
    int t;scanf("%d",&t);
    while(t--){
        scanf("%s",s+1);
        int len=strlen(s+1);
        int j=0;
        for(int i=2;i<=len;i++)
        {
            while(j>0&&s[j+1]!=s[i])
                j=p[j];
            if(s[j+1]==s[i])
                j++;
            p[i]=j;
        }
        int tmp=0;
        int first=1;
        printf("%d\n",len-p[len]);
    }
}
posted @ 2016-10-13 22:04  qscqesze  阅读(574)  评论(0编辑  收藏  举报