POJ-2406 Power Strings(KMP)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

#define maxn 1000005

char ch[maxn];
int next[maxn];
void kmp(char *ch, int len)
{
    next[0] = -1;
    int k = -1, p = 0;

    while(p < len)
    {
        if(k == -1 || ch[p] == ch[k])
        {
            p++;
            k++;
            next[p] = k;
        }
        else 
          k = next[k];
    }
}
int main()
{
// freopen("in.txt", "r", stdin);

    while(gets(ch))
    {
        if(ch[0] == '.' && ch[1] == 0)
            break;
        int len = strlen(ch);
        kmp(ch, len);

        if(len % (len - next[len]) == 0)
          cout << len / (len - next[len]) << endl;
        else
          cout << 1 << endl;    
    }
    return 0;
}

你可能感兴趣的:(POJ-2406 Power Strings(KMP))