题干:
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.
题目大意:
给出定义:字符串相乘"abc" * "def" = "abcdef",给出幂运算的定义,
解题报告:
裸的最小循环节。
AC代码:
#include<set>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#define ll long long
using namespace std;
char s[1000005];
int next[1000005];
int len;
void getnext() {
int k = -1,j = 0;
next[0]=-1;
while(j<len) {
if(k == -1 || s[j] == s[k]) {
j++;k++;
next[j]=k;
}
else k=next[k];
}
}
int main()
{
while(~scanf("%s",s)) {
if(s[0] == '.') break;
memset(next,0,sizeof next);
len = strlen(s);
getnext();
if(len % (len - next[len]) == 0) printf("%d\n",len/(len-next[len]));
else puts("1");
}
return 0;
}
总结:
1.注意那个else put("1")那里,要想清楚为什么会有这种情况发生。不光是因为 没有循环节 的情况(因为没有循环节有的也是要进入那个if的,,因为next[len]可以只要不是起始位置,就最小是0啊,所以也可以进入if,比如"as"这个字符串)。如果是"asa"这样的字符串就比较尴尬了,,想想为啥吧,,,,反正只有这类的情况才会进入else,,并不是所有没有循环节的情况都是进入else的。。。其实看下面那个总结也可以看出来。,,就是 完全没有循环节的 是直接next[len]=0,但是如果有一部分循环节,那就比较尴尬了 。。。详情看下面的那两个例子。
2.举两个例子帮助理解一类新的问题:(这种就属于没有循环节的,但是如果想要凑成循环节,还需要加的单词数)
abdabdab len:8 next[8]:5
最小循环节长度:3(即abd) 需要补的个数是1 d
ababa len:5 next[5]:3
最小循环节长度:2(即ab) 需要补的个数是1 b
符合 len% ( len- next[i] ) == 0 && next[len] != 0 , 则说明字符串循环,而且
循环节长度为: len- next[i]
循环次数为: len/ ( len- next[i] )