HDU1711

本文深入探讨了KMP算法的原理与应用,通过HDU1711题目实例,详细解析了如何将传统的字符串匹配算法应用于数字序列,提供了完整的C++实现代码,并附有详细的注释说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HDU 1711

KMP裸题了,只不过把字符改成数字。

/*
 * @Author: hesorchen
 * @Date: 2020-07-02 22:19:34
 * @LastEditTime: 2020-07-11 12:36:53
 * @Description: https://hesorchen.github.io/
 */
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI acos(-1)
#define PB push_back
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000007
#define pll pair<ll, ll>
#define lowbit(abcd) (abcd & (-abcd))
#define max(a, b) ((a > b) ? (a) : (b))
#define min(a, b) ((a < b) ? (a) : (b))

#define IOS                      \
    ios::sync_with_stdio(false); \
    cin.tie(0);                  \
    cout.tie(0);
#define FRE                              \
    {                                    \
        freopen("in.txt", "r", stdin);   \
        freopen("out.txt", "w", stdout); \
    }

inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9')
    {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')
    {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}
//==============================================================================

ll nxt[1000010];
ll a[1000010], b[1000010];
ll lena, lenb;

void get_nxt()
{
    int j = 0, k = -1;
    nxt[0] = -1;
    while (j < lenb)
    {
        if (k == -1 || b[j] == b[k])
            nxt[++j] = ++k;
        else
            k = nxt[k];
    }
}
int KMP()
{
    get_nxt();
    ll i = 0, j = 0;
    while (i < lena)
    {
        if (j == -1 || a[i] == b[j])
            i++, j++;
        else
            j = nxt[j];
        if (j == lenb)
            return i - j + 1;
    }
    return 0;
}

int main()
{
    IOS;
    ll n;
    cin >> n;
    while (n--)
    {
        cin >> lena >> lenb;
        for (int i = 1; i <= lena; i++)
            cin >> a[i - 1];
        for (int i = 1; i <= lenb; i++)
            cin >> b[i - 1];
        cout << (KMP() ? KMP() : -1) << endl;
    }
    return 0;
}
/*
ababa
aba
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hesorchen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值