http://www.codeforces.com/problemset/problem/182/D
利用到KMP的周期性。现寻找最小周期,再进行扩充。
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <algorithm> #include <math.h> #include <fstream> #include <vector> #include <map> #include <queue> #include <stack> #include <math.h> #include <stdlib.h> using namespace std ; const int maxn = 100005; int n; char s1[maxn],s2[maxn]; int p1[maxn],p2[maxn]; void getnext(char *str,int *next){ int i = 0,j = -1; next[0] = -1; int len = strlen(str); while(i < len){ if(j == -1 || str[i] == str[j]) next[++i] = ++j; else j = next[j]; } } int gcd(int a,int b){ return b?gcd(b,a%b):a; } int lcm(int a,int b){ return a*b/gcd(a,b); } int main(){ while(~scanf("%s%s",s1,s2)){ getnext(s1,p1); getnext(s2,p2); int len_s1 = strlen(s1); int len_s2 = strlen(s2); int t1,t2; if(len_s1%(len_s1 - p1[len_s1]) == 0) t1 = len_s1 - p1[len_s1]; else t1 = len_s1; if(len_s2%(len_s2 - p2[len_s2]) == 0) t2 = len_s2 - p2[len_s2]; else t2 = len_s2; //printf("%d %d\n",p2[len_s2],t2); if(t1 == len_s1&&t2 == len_s2){ if(strcmp(s1,s2) == 0) printf("1\n"); else printf("0\n"); } else if(t1 == len_s1){ if(t2 == len_s1){ int flag = 1; for(int i = 0;i < len_s1;i++) if(s1[i] != s2[i]){ flag = 0; break; } if(flag) printf("1\n"); else printf("0\n"); } else printf("0\n"); } else if(t2 == len_s2){ if(t1 == len_s2){ int flag = 1; for(int i = 0;i < len_s2;i++) if(s1[i] != s2[i]){ flag = 0; break; } if(flag) printf("1\n"); else printf("0\n"); } else printf("0\n"); } else{ int temp = lcm(t1,t2); if(temp > len_s1 || temp > len_s2){ printf("0\n"); continue; } int flag = 0; for(int i = 0;i < temp;i++) if(s1[i] != s2[i]) flag = 1; if(flag){ printf("0\n"); continue; } int ans = 0; int lc = temp; while(temp<=len_s1&&temp<=len_s2){ if(len_s1%temp == 0 && len_s2%temp == 0) ans++; temp += lc; } printf("%d\n",ans); } } return 0 ; }