洛谷p4391 无限传输

考察字符串周期的题
题目链接

结论

要求字串 s s s的最短循环字串长就是: a n s = n − p m t [ n ] ans=n-pmt[n] ans=npmt[n]
证明如下:
洛谷p4391 无限传输_第1张图片这是最大的前缀和后缀
现在我们做如下操作:
洛谷p4391 无限传输_第2张图片
补全字段 a a a和字段 b b b,按子段 a a a的长度人为分开并标号
上下对应相等,所以1等于a
因为公共前后缀,所以1等于7

所以红色字段是最大循环字串

ACcode

#include

using namespace std;

const int M = 1e6 + 9;
int pmt[M];

void get_pmt(const string& p) {
    for (int i = 1, j = 0;i < p.size();i++) {
        while (j && p[i] != p[j])j = pmt[j - 1];
        if (p[i] == p[j])j++;
        pmt[i] = j;
    }
}

int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n;cin >> n;
    string str;cin >> str;
    get_pmt(str);
    cout << n - pmt[n - 1];
    return 0;
}

你可能感兴趣的:(kmp专题,kmp,失配数组,字符串)