题目来源:http://codeforces.com/contest/182/problem/D
D. Common Divisors
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Vasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.
String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors — "ab" and "abab".
Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.
Input
The first input line contains a non-empty string s1.
The second input line contains a non-empty string s2.
Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.
Output
Print the number of common divisors of strings s1 and s2.
Sample test(s)
input
abcdabcd
abcdabcdabcdabcd
output
2
input
aaa
aa
output
1
Note
In first sample the common divisors are strings "abcd" and "abcdabcd".
In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 100010;
void Get_Next(char* str, int* next)
{
int Len = strlen(str);
int i = 0, j = -1;
next[0] = -1;
while(i < Len)
{
if(j == -1 || str[i] == str[j])
{
++i, ++j;
next[i] = j;
}
else
j = next[j];
}
}
int main()
{
char str1[MAXN], str2[MAXN];
char s1[MAXN], s2[MAXN];
int next1[MAXN], next2[MAXN];
int Len1, Len2, i, iMin1, iMin2, num;
while(~scanf("%s %s", str1, str2))
{
Len1 = strlen(str1);
Len2 = strlen(str2);
Get_Next(str1, next1);
Get_Next(str2, next2);
iMin1 = iMin2 = 0;//找出两个串的最小周期
if(2*next1[Len1] < Len1)
iMin1 = Len1;
else
{
if(Len1 % (Len1 - next1[Len1]) == 0)
iMin1 = Len1 - next1[Len1];
else
iMin1 = Len1;
}
if(2*next2[Len2] < Len2)
iMin2 = Len2;
else
{
if(Len2 % (Len2 - next2[Len2]) == 0)
iMin2 = Len2 - next2[Len2];
else
iMin2 = Len2;
}
num = 0;
if(iMin1 != iMin2)//如果两个串的最小周期都不相同那么他们根本就不存在公共因子
{
printf("0\n");
continue ;
}
for(i = 0; i < iMin1; ++i)//判断两个串的最小周期所对应的字串是否相等,不相等直接输出0,相等则在判断
s1[i] = str1[i];
for(i = 0; i < iMin2; ++i)
s2[i] = str2[i];
num = 0;
if(strcmp(s1, s2) == 0)//如果相同
{
num++;
i = 2;
while(i*iMin1 <= Len1 && i*iMin1 <= Len2)//看2倍的周期,3倍的周期·····是否也满足下列条件
{
if(Len1%(i*iMin1) == 0 && Len2%(i*iMin1) == 0)//如果n倍的周期所对应的字串是一个公共因子,那么他就要满足if中的条件
num++;
i = i+1;
}
}
printf("%d\n", num);
}
return 0;
}