Codeforces Round #117 (Div. 2)-D. Common Divisors(KMP)

原题链接

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.

Examples
input
abcdabcd
abcdabcdabcdabcd
output
2
input
aaa
aa
output
1
用KMP求出每个字符串的next数组,再求字符串s的最小divisors的长度,设字符串长度len, divisor长度d = len - next[len], 若len % d != 0, 则d = len

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#define maxn 1000005
#define MOD 1000000007
using namespace std;
typedef long long ll;

char s1[maxn], s2[maxn];
int next1[maxn], next2[maxn];
void KMP(char *str, int *next){
	
	int i = 0, k = -1;
	next[0] = -1;
	while(str[i]){
		if(k == -1 || str[k] == str[i]){
			k++;
			i++;
			next[i] = k;
		}
		else
		 k = next[k];
	}
}
int main(){
//	freopen("in.txt", "r", stdin);
	scanf("%s%s", s1, s2);
	KMP(s1, next1);
	KMP(s2, next2);
	int len1 = strlen(s1);
	int len2 = strlen(s2);
	int m1 = len1 - next1[len1];
	int m2 = len2 - next2[len2];
	if(len1 % m1 == 0){
		s1[m1] = 0;
		m1 = len1 / m1;
	}
	else{
		m1 = 1;
	}
	if(len2 % m2 == 0){
		s2[m2] = 0;
		m2 = len2 / m2;
	}
	else{
		m2 = 1;
	}
	if(strcmp(s1, s2)){
		puts("0");
	}
	else{
	    int ans = 0;
	    for(int i = 1; i <= min(m1, m2); i++){
	    	if(m1 % i == 0 && m2 % i == 0)
	    	 ans++;
	    }
	    printf("%d\n", ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值