Common Divisors
3945 단어 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.
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
");
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
", num);
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
알고리즘 - Knuth, Morris, Prett흔히 찾는 문자나 문자열이 있는 지 없는 지를 확인할 때는 주로 if pattern in words 이런 식으로 검사를 할 수 있다. pi 테이블은 찾으려는 문자열(pattern)의 정보를 저장하고 있는 배열, 자료...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.