Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27028 Accepted Submission(s): 11408
Problem Description
Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
Input
The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
Sample Output
6
-1
Source
题目链接:
分析:KMP裸题,自己看吧,不会的看我博客详解!此题有道坑点就是读入不能用cin读入,很容易T!
纯粹要看运气才会过QAQ
优化以后:
速度快了将近3.5s,scanf大法好啊
下面给出AC代码:
1 #include2 using namespace std; 3 const int N=1000050; 4 inline int read() 5 { 6 int x=0,f=1; 7 char ch=getchar(); 8 while(ch<'0'||ch>'9') 9 { 10 if(ch=='-') 11 f=-1; 12 ch=getchar(); 13 } 14 while(ch>='0'&&ch<='9') 15 { 16 x=x*10+ch-'0'; 17 ch=getchar(); 18 } 19 return x*f; 20 } 21 int kmpnext[N]; 22 int s[N],t[N];///s为主串,t为模式串 23 int slen,tlen;///slen为主串的长度,tlen为模式串的长度 24 inline void getnext() 25 { 26 int i,j; 27 j=kmpnext[0]=-1; 28 i=0; 29 while(i 0&&s[i]!=t[j]) 82 j=kmpnext[j]; 83 if(s[i]==t[j]) 84 j++; 85 if(j==tlen) 86 { 87 ans++; 88 j=kmpnext[j]; 89 } 90 } 91 return ans; 92 } 93 int T; 94 int main() 95 { 96 T=read(); 97 while(T--) 98 { 99 slen=read();100 tlen=read();101 for(int i=0;i