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