hdu 1711 Number Sequence KMP入门题

来源:互联网 发布:手机没有usb共享网络 编辑:程序博客网 时间:2024/06/05 10:13


Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 27074    Accepted Submission(s): 11428


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
213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 2 1
 

Sample Output
6-1
 

Source
HDU 2007-Spring Programming Contest 


题意:要求输出主串中第一个匹配的位置,没有输出-1。



#include<cstdio>#include<string>#include<cstring>#include<iostream>#include<cmath>#include<algorithm>#include<vector>using namespace std;#define all(x) (x).begin(), (x).end()#define for0(a, n) for (int (a) = 0; (a) < (n); (a)++)#define for1(a, n) for (int (a) = 1; (a) <= (n); (a)++)#define mes(a,x,s)  memset(a,x,(s)*sizeof a[0])#define mem(a,x)  memset(a,x,sizeof a)#define ysk(x)  (1<<(x))typedef long long ll;//const int INF = 0x3f3f3f3f ;const int maxn= 1000000 ;int n,m;int a[maxn+3],b[maxn+3],nex[maxn+3];void get_next(){nex[1]=0;int p=0;for(int i=1;i<=m;i++){while( b[i]!=b[p]&&p )  p=nex[p];nex[i+1]=++p;}}int KMP(){int p=1;for(int i=1;i<=n;i++){while(a[i]!=b[p]&&p)  p=nex[p];if(++p==m+1)  return i-m+1;}return -1;}int main(){int T;scanf("%d",&T);while(T--){scanf("%d%d",&n,&m);for1(i,n) scanf("%d",&a[i]);for1(i,m) scanf("%d",&b[i]);get_next();printf("%d\n",KMP());}return 0;}