您的位置:首页 > 产品设计 > UI/UE

Hdu-1711 Number Sequence

2011-11-11 13:49 260 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

题目大意:

从s串中如果能找出p串,则输出p串在s串的位置(两个串下标都从1开始)

解题思路:

KMP算法的简单模拟

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int s[1000010], p[10010];
int nextval[10010];
int num1, num2;

void getnext(const int *p)
{
    int i = 0, j = -1;
    nextval[0] = -1;
    while(i != num2)
    {
        if(j == -1 || p[i] == p[j])
        {
            ++i, ++j;
            if(p[i] != p[j])
                nextval[i] = j;
            else
                nextval[i] = nextval[j];
        }
        else
            j = nextval[j];
    }
}

int KMP(const int *s, const int *p)
{
    int i = 0, j = 0;
    while(i != num1 && j != num2)
    {
        if(s[i] == p[j])
            ++i, ++j;
        else
        {
            if(nextval[j] == -1)
                ++i, j = 0;
            else
                j = nextval[j];
        }
    }
    if(j == num2)
        return i - j + 1;
    else
        return -1;
}

int main()
{
    int ncase, i;
    int res;
    scanf("%d", &ncase);
    while(ncase--)
    {
        scanf("%d%d", &num1, &num2);
        for(i = 0; i < num1; ++i)
            scanf("%d", &s[i]);
        for(i = 0; i < num2; ++i)
            scanf("%d", &p[i]);
        getnext(p);
        res = KMP(s, p);
        if(res == -1)
            printf("-1\n");
        else
            printf("%d\n", res);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: