1. 程式人生 > >2406】Power Strings (KMP,最小迴圈節)

2406】Power Strings (KMP,最小迴圈節)

題幹:

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