HDU 1711 Number Sequence【KMP】【模板题】【水题】(返回匹配到的第一个字母的位置)

时间:2022-03-27 05:43:43

Number Sequence

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


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
返回匹配到的第一个字母的位置

#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <queue>
#include <stack>
#define INF 0x3f3f3f3f
#define ms(x,y) memset(x,y,sizeof(x))
using namespace std;

typedef long long ll;

const double pi = acos(-1.0);
const int mod = 1e9 + 7;
const int maxn = 1e5 + 10;

int nextval[1000010];
int s[1000010], p[10010];
int slen, plen;

//p为模式串
void getnext(int p[], int nextval[])      //朴素kmp,nextval[i]即为1~i-1的最长前后缀长度
{
    int len = plen;
    int i = 0, j = -1;
    nextval[0] = -1;
    while (i < len)
    {
        if (j == -1 || p[i] == p[j])
        {
            nextval[++i] = ++j;
        }
        else
            j = nextval[j];
    }
}

//在s中找p出现的位置
int KMP(int s[], int p[], int nextval[])
{
    getnext(p, nextval);
    int ans = 0;
    int i = 0;  //s下标
    int j = 0;  //p下标
    int s_len = slen;
    int p_len = plen;
    while (i < s_len && j < p_len)
    {
        if (j == -1 || s[i] == p[j])
        {
            i++;
            j++;
        }
        else
            j = nextval[j];

        if (j == p_len)
        {
            return i - j + 1;
        }
    }

    return -1;
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int t;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d%d", &slen, &plen);
        for (int i = 0; i < slen; i++) scanf(" %d", &s[i]);
        for (int i = 0; i < plen ; i++) scanf(" %d", &p[i]);
        printf("%d\n", KMP(s, p, nextval));
    }
    return 0;
}