Common Divisors

3945 단어 KMP
제목: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
"); 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; }

좋은 웹페이지 즐겨찾기