CodeForces 182D(#117)|Common Divisors|KMP求循环节

题目大意

给出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 &times) {
    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”.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值