POJ 2406 Power Strings

G - Power Strings 

                                 POJ - 2406

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.

一开始理解错题意了,结果当然是wa,然后实在受不了就百度了一下,发现大家都在用一个什么定理,我还没找到那个定理是啥,不知道是不是真的是某个定理,也没有人解释一下,不过很好理解,假设S的长度为len,则S存在循环子串,当且仅当,len可以被len - next[len]整除,最短循环子串为S[len - next[len]],对这就是那个定理,其实很好理解的

这道题判断有几个循环的部分,除了循环没有冗余的元素,要求判断整个字符串有几个循环节,假设字符串为 a b c a b c的话对应的next数组应为-1 0 0 0 1 2,而next[6] = 3,如果是a b c a b c a b c的话对应的next数组应该是-1 0 0 0 1 2 3 4 5 而next[9] = 6,其实我想表达的就是如果这是一个循环字符串,那么next[len] = 总长度 - 减去单个循环节的长度,所以单个循环节的长度为 len - next[len],这样总的循环节个数为len /(len - next[len])

然而如果是aabbaa这种的应该怎么判断呢,其对应的next数组应该是-1 0 1 0 0 1然后next[6] = 2,此时判断时6%4 != 0,然而我怎么知道模数一定无法被整除呢,万一不是4是2呢,反正可以确定2是正确的情况,怎么证明出这个定理来还要好好想想啊

其实就是很简单,所以这道题告诉我说学好英语读懂题很重要(看备注说不定能看出来做这道题时心塞的心路历程)

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
char a[1000010];
int ne[1000010];
void findnext()
{
    int i = 0, j = -1;
    ne[0] = -1;
    int len = strlen(a);
    while(i < len)
    {
        if(j == -1 || a[i] == a[j])
            ne[++i] = ++j;
        else j = ne[j];
    }
}
int main()
{
    while(scanf("%s",a))
    {
        int len = strlen(a);
        if(a[0] == '.')break;
        findnext();
//        int maxy = -2;
 //       for(int i = 0; i < len; i ++)
//            if(ne[i] > maxy)
//            maxy = ne[i];


        if(len%(len - ne[len ]))
//        if(ne[len] == 0)
         printf("1\n");

        else printf("%d\n",len/(len - ne[len ]));
    }
    return 0;
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值