hdu1711kmp

Given two sequences of numbers : a11, a22, ...... , aNN, and b11, b22, ...... , bMM (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make aKK = b11, aK+1K+1 = b22, ...... , aK+M?1K+M?1 = bMM. If there are more than one K exist, output the smallest one.

InputThe 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 a11, a22, ...... , aNN. The third line contains M integers which indicate b11, b22, ...... , bMM. All integers are in the range of ?1000000,1000000?1000000,1000000. 
OutputFor 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题意:就是把字符串匹配变成了数组匹配题解:kmp就行(经典的看毛片算法)参考的这位大牛的博客,讲的很清楚http://blog.csdn.net/starstar1992/article/details/54913261

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define pi acos(-1)
#define ll long long
#define mod 1000000007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1

using namespace std;

const double g=10.0,eps=1e-9;
const int N=1000000+5,maxn=10000+5,inf=0x3f3f3f3f;

int ext[N],str[maxn],ptr[N];
void getnext(int slen)
{
    ext[0]=-1;
    int k=-1;
    for(int i=1;i<=slen-1;i++)
    {
        while(k>-1&&str[k+1]!=str[i])k=ext[k];
        if(str[k+1]==str[i])k++;
        ext[i]=k;
    }
}
int kmp(int plen,int slen)
{
    int k=-1;
    for(int i=0;i<=plen-1;i++)
    {
        while(k>-1&&str[k+1]!=ptr[i])k=ext[k];
        if(str[k+1]==ptr[i])k++;
        if(k==slen-1)return i-slen+2;
    }
    return -1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
 //   cout<<setiosflags(ios::fixed)<<setprecision(2);
    int t,n,m;
    cin>>t;
    while(t--){
        cin>>n>>m;
        for(int i=0;i<n;i++)cin>>ptr[i];
        for(int i=0;i<m;i++)cin>>str[i];
        getnext(m);
        cout<<kmp(n,m)<<endl;
    }
    return 0;
}

时间: 2024-10-10 08:49:48

hdu1711kmp的相关文章

hdu--1711--kmp应用在整形数组--Number Sequence

/* Name: hdu--1711--Number Sequence Author: shen_渊 Date: 16/04/17 19:58 Description: 第一次知道,KMP能用在整形数组 o(╯□╰)o */ #include<cstring> #include<iostream> using namespace std; int kmp(); void getFail(); int n,m; int s1[1000009],s2[10009]; int f[100