POJ 2406 Power Strings(KMP)

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 1000010


char 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值