题目大意
给出s1和s2,求两字符串公共循环节个数。
题解
求最小循环节的方法:
http://blog.csdn.net/huanghongxun/article/details/53213871
注意到循环节只有最小的和由最小的重复几次组成的。
所以先求出两串的最小循环节,并判断是否一致,如果不一致就不可能有公共循环节。
如果一致,那么求出两串的循环次数,那么两次数的公共因子的个数就是循环节个数。
#include <cstdio>
#include <cstring>
const int N = 100005;
char s1[N], s2[N];
int f1[N], f2[N];
void getloop(char *p, int n, int *next, int &loop, int ×) {
for (int i = 0, j = 2; j <= n; ++j) {
while (i && p[j] != p[i + 1]) i = next[i];
if (p[j] == p[i + 1]) ++i;
next[j] = i;
}
loop = n - next[n];
if (loop != 0 && n % loop == 0) times = n / loop;
else times = 1, loop = n;
}
int main() {
int n1, n2, l1, l2, i, t1, t2, ans = 0;
scanf("%s%s", s1 + 1, s2 + 1);
n1 = strlen(s1 + 1); n2 = strlen(s2 + 1);
getloop(s1, n1, f1, l1, t1);
getloop(s2, n2, f2, l2, t2);
if (l1 != l2) return puts("0");
for (i = 1; i <= l1; ++i) if (s1[i] != s2[i]) return puts("0");
for (i = 1; i <= t1 && i <= t2; ++i)
if (t1 % i == 0 && t2 % i == 0)
++ans;
printf("%d", ans);
return 0;
}
D. Common Divisors
Description
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.
Examples
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”.