题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3746

题意:

一串字符,只能在串首和串尾添加字符,最少添加几个字符前后字符串连接起来会是一个循环节组成的串

思路:

那么我们最少需要添加的就是循环节大小减去不足循环节的串大小(只需要考虑尾部

i % ( i - next[i] ) == 0 && next[i] != 0 

则说明字符串循环,而且
循环节长度为: i - next[i]
循环次数为: i / ( i - next[i] )
否则的话不循环,至少要添加的就是len
ps:个人存在一个wa点就是string的定义放在main里面就wa放外面就ac希望有明白的大佬指点一下我QAQ…(浪费了我一个小时的时间结果代码改了这个都能a

#include <bits/stdc++.h>
using namespace std;
const int N=2e5+10;
#define end '\n'
#define IOS ios::sync_with_stdio(0)
int nxt[N];
string s;
void get_next(string p) {
    int lenp = p.size();
    int j = 0, k = -1;
    nxt[0] = -1;
    while (j < lenp) {
        if (k == -1 || p[j] == p[k]) {
            nxt[++j] = ++k;
        } else {
            k = nxt[k];
        }
    }
}
int main() {
    IOS;
    int t;
    cin >> t;
    while (t--) {
        cin >> s;
        get_next(s);
        int len = s.size();
        if (nxt[len] == 0) {
            cout << len << end;
            continue;
        }
        int x = len - nxt[len];
        if (len % x == 0) {
            cout << "0" << end;
        } else {
            cout << x - nxt[len] % x << end;
        }
    }
    return 0;
}
/* 3 aaa abca abcde 0 2 5*/