Background
I want to tell you a story. Not entirely, but only the very beginning, because the ending of this story became a legend of programming—as well as its heroes.
When computers were large, when trees were small, when the sun shined brighter… Once upon a time there were Three Programmers. I doubt whether they participated in any programming contests, because there were no contests at that ancient time. There was neither ACM ICPC nor Timus Online Judge. But there were Three Programmers.
Problem
One day Three Programmers invented an amusing game to train memory and mental faculties. The First Programmer thought out a string S which was N characters long and passed it to the Second and the Third Programmers. The Second Programmer executed X (0 ≤ X < N) successive cycle shifts (a cycle shift is a transfer of the last character of the string to the beginning of this string) with this string. As a result of these operations a string T was produced, and the Second Programmer passed it to the Third Programmer. A task of the Third Programmer was to find the number X or make sure that the Second Programmer was mistaken, because the string T could not be produced from the string S via cycle shifts.
The first line contains the integer number N (1 ≤ N ≤ 250000). The second line contains the string S. The third line contains the string T. Each string has length N and may contain any ASCII characters with codes from 33 to 255.
If the string T can be produced from the string S via cycle shifts you should output the desired number X, otherwise you should output “?1”. If the problem has several solutions, you may output any of them.
input | output |
---|---|
11 abracadabra racadabraab |
9 |
Notes
Let us consider the strings S = “abracadabra” and T = “racadabraab”. The string T can be produced from the string S via 9 cycle shifts: “abracadabra” > “aabracadabr” > “raabracadab” > “braabracada” > “abraabracad” > “dabraabraca” > “adabraabrac” > “cadabraabra” > “acadabraabr” > “racadabraab”
题意
把主串后面多长移到前面成为模式串,不可以输出-1;
思路
kmp 返回第一次模式串出现的位置
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char y[510000];
char x[251000];
int ext[251000];
void kmp_pre(int m)
{int i,j;j = ext[0]=-1;i=0;while(i<m){while(-1!=j&&x[i]!=x[j]) j=ext[j];ext[++i] = ++j;}
}int KMP_Count(int m,int n)
{int i,j;kmp_pre(m);i=j=0;while(i<n){while(-1!=j&&y[i]!=x[j]) j=ext[j];i++;j++;if(j==m) break;}return i-m+1;
}
int main()
{int n,i,ans;scanf("%d",&n);scanf("%s",y);scanf("%s",x);for(i=n;i<2*n;i++){y[i] = y[i-n];}memset(ext,0,sizeof(ext));ans = KMP_Count(n,2*n);if(ans==n+1) printf("-1\n");else{if(ans==1) printf("-1\n");else printf("%d\n",n-ans+1);}return 0;
}