前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >hdoj 1711 KMP Number Sequence

hdoj 1711 KMP Number Sequence

作者头像
xindoo
发布2021-01-22 12:59:24
2900
发布2021-01-22 12:59:24
举报
文章被收录于专栏:XINDOO的专栏

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

代码语言:javascript
复制
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

代码语言:javascript
复制
6
-1
#include <stdio.h>

int n, m;
int a[1000005];
int b[10005];
int f[10005];

void getfail()
{
    f[0] = 0;
    f[1] = 0;
    for (int i = 1; i < m; i++)
    {
        int j = f[i];
        while (j && b[i] != b[j])
            j = f[j];
        f[i+1] = b[j] == b[i] ? j + 1 : 0;
    }
}

int main()
{
    int flag, i, j, t;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d %d",&n,&m);
        for (i = 0; i < n; i++)
            scanf("%d",&a[i]);
        for (i = 0; i < m; i++)
            scanf("%d",&b[i]);
        getfail();
        for (i = 0;i <= m; i++) printf("%d ",f[i]);  puts("");
        flag = 1;
        j = 0;
        for (i = 0;i < n;i++)
        {
            while (j && b[j] != a[i])
                j = f[j];
            if (b[j] == a[i])
                j++;
            if (j == m)
            {
                flag = 0;
                printf("%d\n",i - m + 1);
            }
        }
        if (flag)
            puts("-1");
    }
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-02-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档