HUST 1010 (KMP 水~)

1010 - The Minimum Length

时间限制:1秒 内存限制:128兆

1693 次提交 623 次通过
题目描述
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.
输入
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.
输出
For each line, output an integer, as described above.
样例输入
bcabcab
efgabcdefgabcde
样例输出
3
7


题意:有一个串A,用A作为循环节构造无穷长的串C:AAAAAA....,然后截取中间的一

段串B,求最短的A。

容易发现B中的最小循环节长度就是A的最短长度,于是直接n-next[n]。

#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
#define maxn 1111111

char T[maxn];
int n;
#define next Next
int next[maxn];

void get_next (char *p) {  
    int m = strlen (p);
    int t;  
    t = next[0] = -1;  
    int j = 0;  
    while (j < m) {  
        if (t < 0 || p[j] == p[t]) {//匹配  
            j++, t++;  
            next[j] = t;
        }  
        else //失配  
            t = next[t];  
    } 
}  

int main () {
    while (scanf ("%s", T) == 1) {
        get_next (T); 
        n = strlen (T);
        printf ("%d\n", n-next[n]);
    }
    return 0;
}


你可能感兴趣的:(HUST 1010 (KMP 水~))