# 循环移位(Cycle)

2021-11-27 21:02:36  阅读：37  来源： 互联网

### 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

### 限制

0 ≤ m ≤ 5000

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

``` 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 }```