循环移位(Cycle)

 


Description

Cycle shifting refers to following operation on the sting. Moving first letter to the end and keeping rest part of the string. For example, apply cycle shifting on ABCD will generate BCDA. Given any two strings, to judge if arbitrary times of cycle shifting on one string can generate the other one.

Input

There m lines in the input, while each one consists of two strings separated by space. Each string only contains uppercase letter 'A'~'Z'.

Output

For each line in input, output YES in case one string can be transformed into the other by cycle shifting, otherwise output NO.

Example

Input

AACD CDAA
ABCDEFG EFGABCD
ABCD ACBD
ABCDEFEG ABCDEE

Output

YES
YES
NO
NO

Restrictions

0 <= m <= 5000

1 <= |S1|, |S2| <= 10^5

Time: 2 sec

Memory: 256 MB

描述

所谓循环移位是指。一个字符串的首字母移到末尾, 其他字符的次序保持不变。比如ABCD经过一次循环移位后变成BCDA

给定两个字符串,判断它们是不是可以通过若干次循环移位得到彼此

输入

由m行组成,每行包含两个由大写字母'A'~'Z'组成的字符串,中间由空格隔开

输出

对于每行输入,输出这两个字符串是否可以通过循环移位得到彼此:YES表示是,NO表示否

样例

见英文题面

限制

0 ≤ m ≤ 5000

1 ≤ |S1|, |S2| ≤ 10^5

时间:2 sec

内存:256 MB

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #define N 200005
 5 using namespace std;
 6 
 7 void getNext(int Next[],char b[],int len)
 8 {
 9     memset(Next,0,sizeof(Next));
10     Next[0]=-1;
11     for(int i=0,j=-1;i<len;)
12     if(j==-1||b[i]==b[j])
13     Next[++i]=++j;
14     else
15     j=Next[j];
16 }
17 int kmp(char a[],char b[],int Next[])
18 {
19     int n,len;
20     n=strlen(a);
21     len=strlen(b);
22     getNext(Next,b,len);
23     
24     for(int i=0,j=0;i<n;)
25     {
26         if(j==-1||a[i]==b[j])i++,j++;
27         else
28         j=Next[j];        
29         if(j>=len)
30         return 1;
31     }
32     return 0;    
33 }
34 
35 int Next[N];
36 char a[N],b[N];
37 char c[N*2];
38 
39 int main()
40 {
41     while(scanf("%s %s",a,b)==2)
42     {        
43         strcpy(c,a);
44         strcat(c,a);
45         
46         if(strlen(a)==strlen(b)&&kmp(c,b,Next))printf("YES\n");
47         else
48         printf("NO\n");
49     }
50     return 0;
51 }

 

上一篇:docker打开redis 配置


下一篇:二分法找适当最小值问题