HDOJ-1711 (KMP algorithm)

Number Sequence

HDOJ-1711

1. The algorithm used here is the KMP algorithm, pi is an array of prefix array.
2. code to use a technique is to use an array c as a complex string, which add a special integer bit -1000006, because it will never appear in the array.
3. additional note is the need to quickly add the input and output statements, because the amount of data involved a little big, so time out, of course, you can also use scanf can.

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,m;
int a[1000006],b[10004];
int pi[1000006];
int c[1010010];
void Pi(int len){
    memset(pi,0,sizeof(pi));
    int n=len;
    pi[0]=0;
    for(int i=1;i<n;i++){
        int j=pi[i-1];
        while(j>0&&c[i]!=c[j]){
            j=pi[j-1];
        }
        if(c[i]==c[j])
            j++;
        pi[i]=j;
    }
}
int main(){
    ios::sync_with_stdio(false);//不加这两条语句会超时
    cin.tie(0);
    int t;
    cin>>t;
    while(t--){
        cin>>n>>m;
        int a1,b1;
        for(int i=0;i<n;i++){
           cin>>a[i];
           c[i]=a[i];
        }
        for(int j=0;j<m;j++){
            cin>>b[j];
            c[j]=b[j];
        }
        c[m]=-1000006;
        for(int i=m+1;i<n+m+1;i++){
           c[i]=a[i-m-1];
        }
        Pi(m+n+1);
        int ans=-1;
        for(int i=m+1;i<n+1+m;i++){
            //cout<<pi[i]<<endl;
            if(pi[i]==m){
                ans=i-(m-1)-(m+1);
                ans++;
                break;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/GarrettWale/p/11325195.html