欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Power Strings.0 KMP

程序员文章站 2022-04-01 19:49:23
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 = “” (t...

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.

在这里插入代码#include<iostream> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; char f[1001000]; int m,n,nt[1001000]; void gnt(char f[]) { int i=0,j=nt[0]=-1; while(i<m) { if(j==-1||f[i]==f[j])//不发生匹配或i和j发生匹配要向右移动一位  { i++;j++; nt[i]=j;//最大前缀和最大后缀的匹配长度  } else j=nt[j];//回溯到之前不匹配的位置  } } int main() { while(~scanf("%s",f)) { if(f[0]=='.') break; m=strlen(f); gnt(f); n=m-nt[m];//最小循环节长度  if(m%n==0) printf("%d\n",m/n);//求有几个循环节  else printf("1\n"); } return 0; }

本文地址:https://blog.csdn.net/nearal/article/details/107893068