POJ 2406 Power String(KMP)

来源:互联网 发布:成都美工平均工资 编辑:程序博客网 时间:2024/04/30 11:35

解题思路:

依旧是利用next数组的性质,m % (m - next[m]) == 0;

#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <algorithm>#include <cmath>#include <vector>#include <queue>#include <stack>#define LL long long#define FOR(i,x,y) for(int i=x;i<=y;i++)using namespace std;const int maxn = 1000000 + 10;char s[maxn];int next[maxn];int main(){    while(scanf("%s", s)!=EOF)    {        if(strcmp(s,".") == 0)            break;        int m = strlen(s);        next[0] = 0; next[1] = 0;        for(int i=1;i<m;i++)        {            int j = next[i];            while(j && s[i] != s[j]) j = next[j];            next[i+1] = (s[i] == s[j]) ? j + 1 : 0;        }        int ans = 1;        if(next[m] > 0 && m % (m - next[m]) == 0) ans = m / (m - next[m]);        printf("%d\n", ans);    }    return 0;}

0 0
原创粉丝点击