HUST 1010 (KMP的Next数组应用)

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 abcd  efgabcdefgabcdefgabcdefg.... Then I cut the red part: efgabcdefgabcde as string B. From B, you should find out the shortest A. 

InputMultiply 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. 
OutputFor each line, output an integer, as described above.Sample Input
bcabcab
efgabcdefgabcde
Sample Output
3
7

            好好的想写一个题,发现不给提交,去hust提交连注册都没用,所以写个博客记录一下

            

             这个题目是给定一个由一段字符串A重复组成的字符串B的一部分,且至少包含一个字符串A,求出那个串A的长度

            这个题目再次彰显KMP的强大。。。

             因为是至少包含一个完整的A,所以开头第一个字母与后面组成的一个串长为要求的串A的长度的序列一定与A是同构的,那么由KMP 算    法求得的第m+1位的那个字符的next值与给出的字符串总长的差一定是这个要求的串A的长度。


代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;

char str[maxn];
int Next[maxn], n;

void get_next(){
    Next[0] = -1;
    int j = 0, k = -1;
    while (j < n){
        if (k == -1 || str[j] == str[k]){
            Next[++j] = ++k;
        }
        else k = Next[k];
    }
}

int main (){
    while (~scanf("%s",str)){
        n = strlen(str);
        get_next();
        int ans = n - Next[n];
        printf("%d\n",ans);
    }
    return 0;
}

虽然没有地方提交判断是不是对的,但是个人认为写的没什么错误。哈哈哈。


猜你喜欢

转载自blog.csdn.net/weixin_41190227/article/details/80272034