Gym 101667I Slot Machines——kmp求最小循环节

版权声明:欢迎大家转载,转载请注明出处 https://blog.csdn.net/hao_zong_yin/article/details/82463634
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int n, a[maxn], f[maxn];
char c;
inline void input(int &x) {
    x = 0;
    while ((c = getchar()) < '0' || c > '9');
    while ('0' <= c && c <= '9') x = x * 10 + c - '0', c = getchar();
}
int main() {
    input(n);
    for (int i = n-1; i >= 0; i--) input(a[i]);
    f[0] = f[1] = 0;
    for (int i = 1; i < n; i++) {
        int j = f[i];
        while (j && a[i] != a[j]) j = f[j];
        f[i+1] = (a[i] == a[j] ? j+1 : 0);
    }
    int k = n, p = n;
    for (int i = 1; i <= n; i++) {
        int kk = n - i, pp = i - f[i];
        if (kk + pp < k + p) { k = kk; p = pp; }
        else if (kk + pp == k + p && pp < p) { k = kk; p = pp; }
    }
    printf("%d %d\n", k, p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hao_zong_yin/article/details/82463634