POJ 2406 Power Strings(KMP)

来源:互联网 发布:mac 启动 磁盘工具 编辑:程序博客网 时间:2024/05/16 17:59

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 44033 Accepted: 18369
Description

Given two strings a and b we define a*b to be their concatenation. For example, if a = “abc” and b = “def” then a*b = “abcdef”. If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = “” (the empty string) and a^(n+1) = a*(a^n).
Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output

For each s you should print the largest n such that s = a^n for some string a.
Sample Input

abcd
aaaa
ababab
.
Sample Output

1
4
3
Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

用的是KMP,不过貌似还有别的方法的样子
发现考KMP的不多,考KMP里面 next的倒是蛮多的,不过next是核心,多考考也是正常的,这个next呢,总结一下
通过next可以找到模式串 前缀与主串后缀相等的地方,然后对比下一个,既然可以找到模式串与主串的关系,那么就一定可以找到模式串与模式串的关系,肯定可以找到一个模式串的任何一个位置与其前缀的关系,对比当前位置与next回溯的位置,可以进行很多判断

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define M 1000010char ptr[M];int next[M], plen, num;void getnext(){    int i = 0, k = -1;    next[0] = -1;    while(i < plen)    {        if(k == -1 || ptr[i] == ptr[k])        {            i++, k++;            next[i] = k;        }        else        {            k = next[k];        }    }}int main(){    while(scanf("%s", ptr) && ptr[0] != '.')    {        plen = strlen(ptr);        getnext();        int k = next[plen-1];        if(k == plen - 2 && ptr[plen-1] == ptr[0])//倘若不相等就不对了,下面都是的        {            printf("%d\n", plen);            continue;        }        int ans = 1, slen;        for( ; k>0; k = next[k])        {            slen = plen - 1;            if(plen % (k+1) == 0)            {                slen -= (k+1);                while(next[slen] >= k && ptr[slen] == ptr[plen-1])                {                    slen -= (k+1);                }                if(slen == k && ptr[slen] == ptr[plen-1])                {                    ans = max(ans, plen / (k + 1));                }            }        }        printf("%d\n", ans);    }    return 0;}
0 0
原创粉丝点击