您的位置:首页 > 其它

求最小循环节长度UVA - 455

2018-02-06 18:09 302 查看
A character string is said to have period k if it can be formed by concatenating one or more repetitions

of another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formed

by 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (one

repetition of ”abcabcabcabc”).

Write a program to read a character string and determine its smallest period.

Input

The first line oif the input file will contain a single integer N indicating how many test case that your

program will test followed by a blank line. Each test case will contain a single character string of up

to 80 non-blank characters. Two consecutive input will separated by a blank line.

Output

An integer denoting the smallest period of the input string for each input. Two consecutive output are

separated by a blank line.

Sample Input

1

HoHoHo

Sample Output

2

思路: 暴力枚举循环节长度,循环问题用求模运算

//#define LOCAL/*注意提交时将此行代码注释掉*/
//#include<windows.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int fun(char *str)
{
int k,len=strlen(str);
for(int i=1;i<=strlen(str);i++)
{//i是循序节长度
int flag=1;

if(len%i==0)
{
for(k=i;k<len;k++)
{
if(str[k]!=str[k%i])//循环用求模运算   使得后面的字符与最初的循环体进行比较
{
flag=0;
break;
}
}
if(flag)
return i;
}
}
return len;
}
int main()
{
//读写文件代码写在这里不会影响计时函数
#ifdef LOCAL
freopen( "input.txt", "r", stdin );
freopen( "output.txt", "w", stdout );
#endif // LOCAL

/*计时函数*/
#ifdef LOCAL
DWORD start_time, end_time;
start_time = GetTickCount();
#endif // LOCAL
/*main函数主体*/

int N;
int flag=0;
cin >> N;
//getchar();
char str[100];
while(N--)
{
cin >> str;
cout << fun(str) << endl;
if(N)
cout<<endl;

}

#ifdef LOCAL
end_time = GetTickCount();
//提交时将时间函数输出注释掉
cout << "Running time is: " << static_cast<double>( end_time - start_time ) * 1.0 / 1000 << "ms" << endl; //输出运行时间
#endif // LOCAL
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm题解