HUST 1010-The Minimum Length-KMP

kewlgrl發表於2015-11-03
The Minimum Length
Time Limit:1000MS    Memory Limit:131072KB    64bit IO Format:%lld & %llu

Description

There is a string A. The length of A is less than 1,000,000. I rewrite it again and again. Then I got a new string: AAAAAA...... Now I cut it from two different position and get a new string B. Then, give you the string B, can you tell me the length of the shortest possible string A. For example, A="abcdefg". I got abcdefgabcdefgabcdefgabcdefg.... Then I cut the red part: efgabcdefgabcde as string B. From B, you should find out the shortest A.

Input

Multiply Test Cases. For each line there is a string B which contains only lowercase and uppercase charactors. The length of B is no more than 1,000,000.

Output

For each line, output an integer, as described above.

Sample Input

bcabcab
efgabcdefgabcde

Sample Output

3
7



有一個字串,長度小於1000000。我一遍又一遍的重寫。然後我有了一個新的字串:aaaaaa ......現在我把它從兩個不同的位置,得到一個新的字串,然後,給你的字串B,你能告訴我,例如最短的字串的長度,A="abcdefg". I got abcdefgabcdefgabcdefgabcdefg....…然後我把紅色部分:efgabcdefgabcde作為字串B,你應該找出最短的A.

多試驗例。每一行有一個字串B只包含小寫和大寫。長度不超過1000000。


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxt=1000000+10;
char t[maxt];
int next[maxt];
int main()
{
    while(scanf("%s",t)!=EOF)
    {
        int p=0,cur,l;
        next[0]=-1;
        next[1]=0;
        l=strlen(t);
        for(cur=2; cur<=l; ++cur)
        {
            while(p>=0&&t[p]!=t[cur-1])
                p=next[p];
            next[cur]=++p;
        }
        printf("%d\n",l-next[l]);
    }
    return 0;
}

KMP模板題,呼叫求子模板串的模式值next[n],再用串的長度減去next[n]即得到答案。

相關文章