Power Strings

Description

- 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 1

- abcd
aaaa
ababab
.

Sample Output 1

- 1
4
3

思路1

暴力

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std; const int Max=1000001;
string a;
int x,n,m;
int p[Max]; void prime(int n)
{
int k=(int)sqrt(n*1.0);
p[1]=1;
for(int i=2; i<=k; i++)
if(n%i==0)
p[++m]=i;
int end=m;
if(k*k==n) end--;
for(int i=end; i>=1; i--)
p[++m]=n/p[i];
} bool ok(int x)
{
string s=a.substr(0,x);
for(int i=0; i<a.size(); i+=x)
if(s!=a.substr(i,x)) return false;
return true;
} int main()
{
while(getline(cin,a))
{
x=1,n=a.size();m=1;
prime(n);
while(x<=m)
{
if(ok(p[x]))
{cout<<a.size()/p[x]<<endl;break;}
x++;
}
}
return 0;
}

思路2

利用\(KMP\)的\(next[]\)数组

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std; const int Max=1000001;
string a;
int N,M,ans,nx[Max]; void makenx(int M)
{
memset(nx,0,sizeof(nx));
int i=0,j=-1;
nx[i]=j;
while(i<M)
{
if(j==-1||a[i]==a[j]) i++,j++,nx[i]=j;
else j=nx[j];
}
} int main()
{
bool fl;
while(getline(cin,a)&&a[0]!='.')
{
fl=true;
M=a.size();makenx(M);
if(M%(M-nx[M])==0) cout<<M/(M-nx[M])<<endl;
else cout<<1<<endl;
}
return 0;
}

最新文章

  1. 【bzoj1725】[USACO2006 Nov]Corn Fields牧场的安排
  2. akka各模块
  3. js 重点 (转载)
  4. ADC 分辨率和精度的区别
  5. [SSH 2] 以网站主页面浅谈Struts2配置
  6. spark处理jsonFile
  7. hackerrank【Lego Blocks】:计数类dp
  8. c++11-bind的用法
  9. redis安装(针对2.8以上版本)
  10. 个人版整理APP测试流程
  11. JS正则校验
  12. npm install 报错ERR! 404 Not Found: event-stream@3.3.6
  13. WampServer在win10系统下安装的坑
  14. 5-4 import,export属性
  15. Day 7 深copy和浅Copy
  16. python接口自动化6-重定向(Location)
  17. sqlserver安装遇到的问题——1
  18. PL\SQL结构控制、异常
  19. ajax-2
  20. POJ - 3261 后缀数组 height应用

热门文章

  1. Nginx 主要应用场景
  2. Objective-C编程 — 并行编程
  3. 深入源码分析SpringMVC执行过程
  4. fancybox图片灯箱功能
  5. 通配符与标签!important的背景展示,也是让我怀疑人生了
  6. ES6 - 基础学习(4): 模板字符串和字符串新增方法
  7. 【题解】 2月19日 厦门双十中学NOIP2014模拟D2 T1 采药人的切题规则
  8. 03.JS运算符
  9. JS DOM中getElement系列和querySelector系列获取节点
  10. [CF1311B] WeirdSort