gym-101667I Slot Machines
Slot Machines
求字符串后缀的最小循环节(可截断)
\(kmp\)
\(kmp\) 只能在 \(O(n)\) 预处理后 \(O(1)\) 询问最小循环节,因此考虑直接把数组反转,然后询问即可
注意不可以把所有数字省略
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2e6 + 10;
#define pii pair<int, int>
int num[maxn], nex[maxn];
void get_next(int n)
{
int i = 0, j = -1;
nex[0] = -1;
while(i < n)
{
if(j == -1 || num[i] == num[j])
nex[++i] = ++j;
else
j = nex[j];
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
for(int i=n-1; i>=0; i--) cin >> num[i];
get_next(n);
int k = 0, p = n;
for(int i=0; i<n; i++)
{
int kk = n - i - 1;
int pp = i + 1 - nex[i + 1];
if(k + p > kk + pp)
{
k = kk;
p = pp;
}
else if(k + p == kk + pp && pp < p)
{
k = kk;
p = pp;
}
}
cout << k << " " << p << endl;
return 0;
}