您的位置:首页 > 其它

poj 2406 Power Strings(KMP入门,next函数理解)

2015-08-10 17:30 543 查看

Power Strings

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 37685Accepted: 15590
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.
Source

Waterloo local 2002.07.01

基础题目,只要是理解next函数。

#include<iostream>
#include<vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include<algorithm>
#define ll long long
#define eps 1e-8
using namespace std;

int nexts[1050];
char b[1050];

void pre_nexts(int m)
{
memset(nexts,0,sizeof(nexts));
int j = 0,k = -1;
nexts[0] = -1;
while(j < m)
{
if(k == -1 || b[j] == b[k])  nexts[++j] = ++k;
else k = nexts[k];
}
}
int main(void)
{
while(scanf("%s",b),b[0] != '.')
{
int n = (int)strlen(b);
pre_nexts(n);
if(n % (n-nexts
) == 0 && n/(n - nexts
) > 1) printf("%d\n",n/(n-nexts
));
//根据next函数的最后一个匹配数,算出循环节点~
else printf("1\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: