POJ - 2406:Power Strings (求最小循环节)

题目大意:

给你一个串S,问你它的子串最多重复多少次可以得到S串。

解题思路:

这竟然是后缀数组这一节的练习题,明显的kmp求最小循环节。。。

最小循环节:n-next[n]。

顺便吐槽一下 万恶的POJ,不能用 bits/stdc++.h

Ac代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
#include <functional>
#define next ne
#define rank ra
using namespace std;
typedef long long ll;
const int maxn=1e7+5;
char s[maxn];
int next[maxn];
void get_next(char a[])
{
    int l=strlen(a);
    int i=0;
    int j=-1;
    next[0]=-1;
    while(i<l)
    {
        if(j==-1||a[i]==a[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
            j=next[j];
    }
}

int main()
{
    while(scanf(" %s",s)!=EOF)
    {
        int ls=strlen(s);
        if(ls==1&&s[0]=='.') break;
        get_next(s);
        int len=ls-next[ls];    //求出最小循环节长度
        if(len>0&&ls%len==0)    //判断是否合法
            printf("%d\n",ls/len);
        else printf("1\n");
    }
}

猜你喜欢

转载自blog.csdn.net/f2935552941/article/details/81319251