用KMP征服循环节问题

以前我还是写过KMP的文章的

现在我们可以求一下循环节啊

Slot Machines

 Gym - 101667I 

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int a[N],f[N],n;
int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        scanf("%d",&a[n-i-1]);
    f[0]=-1;
    for(int i=0,j=-1; i<n; i++,j++)
    {
        while(j!=-1&&a[j]!=a[i])j=f[j];
        f[i+1]=j+1;
    }
    int k=n,p=n;
    for(int i=n; i>0; i--)
    {
        int tk=n-i,tp=i-f[i];
        if(tp+tk<k+p||tp+tk==k+p&&tp<p)k=tk,p=tp;
    }
    printf("%d %d\n",k,p);
}

猜你喜欢

转载自www.cnblogs.com/BobHuang/p/9450170.html