power strings(对next数组的理解)

E - Power Strings
Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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
题意:求最小子串循环了几次。
知道next数组里存储的是之前最大匹配数(前缀后缀公共子串长度)len(s)-next[len]就是最小循环子串的长度=len2
len(s1)%len2==0说明有循环串

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include
#include
#define N 10000+5
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
int a[1005];
int b[1005];
int mp[105][105];
int vis[105];
int d[105];
int lowcost[105];
int n, m;
int nex[1000005];
char s1[1000005], s2[1000005];
void getnex()
{
	int len2 = strlen(s2);
	memset(nex, -1, sizeof(nex));
	//nex[0] = { -1 };
	int k = -1;
	int j = 0;
	while (j < len2 )
	{
		if (k == -1 || s2[j] == s2[k])
		{
			++k;
			++j;
			nex[j] = k;
		}
		else
		{
			k = nex[k];
		}
	}
}
int kmp()//没用到
{
	int i = 0, j = 0;
	int len1 = strlen(s1);
	int len2 = strlen(s2);
	int ans = 0;
	while (i < len1)
	{
		
		if (j == -1 || s1[i] == s2[j])
		{	
			i++;
			j++;
			
		}
		else
		{
			j = nex[j];
		}
	}
	return j;
}
int main()
{
	int T;
	//scanf("%d", &T);
	while (~scanf("%s", s1))
	{
		if (s1[0] == '.')
			break;
		strcpy(s2, s1);
		getnex();
		
		int len = strlen(s1)-nex[strlen(s1)];
		if (strlen(s1) % len == 0)
			printf("%d\n", strlen(s1) / len);
		else
			printf("1\n");
		

	}
	return 0;
}



你可能感兴趣的:(KMP)