Hdu 1711 KMP算法匹配(水)
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
------------------------- 我是分割线 ----------------------------------------------
第一反应getline()函数读取一行,于是就GG
因为getline函数会将空格也读入。按字符数用scanf()读入后,这也就是kmp匹配的模板题了。
#include <iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int N=100005;
int Next[N];
int ps[N],ts[10*N];
void make_next(int b){
int i=0,k=-1;
Next[0]=k;
while(i<b-1){
//cout<<i<<" "<<k<<endl;
if(k==-1||ps[i]==ps[k])Next[++i]=++k;
else k=Next[k];
}
}
int main() {
int t;scanf("%d",&t);
while(t--){
int a,b;
scanf("%d%d",&a,&b);
for(int i=0;i<a;i++)scanf("%d",&ts[i]);
for(int j=0;j<b;j++)scanf("%d",&ps[j]);
make_next(b);
//for(int i=0;i<b;i++)cout<<Next[i]<<" ";
int i=0,j=0,flag=0,ans=-1;
while(i<a){
if(j==-1||ps[j]==ts[i]){
i++;j++;
}
else j=Next[j];
if(j==b){
ans=i-b+1;
break;
}
}
cout<<ans<<endl;
}
return 0;
/*getline(cin,ps);
make_next();*/
}