hdu-1711(hash)

题意:给你T组数据,每组数据分别输入n,m和长度为n的数字数组,和长度为m的数字数组,问你长度为m的数组第一次出现在长度为n的数组的位置

解题思路:标准字符串匹配问题,一般用kmp解,拿来练hash

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
const ll p=133331;
const int M=1e6+100;
const int N=1e4+100;
ll h[M];
ll a[N],b[M];
ll lena,lenb,t,n,m;
ll pp[N];
ll juage(ll l,ll r)
{
    ll tmp=(h[r]-(h[l-1]*pp[r-l+1])%mod)%mod;
    while(tmp<0)
        tmp+=mod;
    return tmp;
}
int main()
{
    cin>>t;
    while(t--)
    {
        memset(h,0,sizeof(h));
        cin>>m>>n;
        ll ans=0;
        pp[0]=1;
        for(int i=1;i<=n;i++)
            pp[i]=(pp[i-1]*p)%mod;
        for(int i=1;i<=m;i++)
        {
            cin>>b[i];b[i]+=1000000;
            h[i]=(h[i-1]*p+b[i])%mod;
        }
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];a[i]+=1000000;
            ans=(ans*p+a[i])%mod;
        }
        int sc=-1;
        for(int i=1;i<=m;i++)
        {
            if((i+n-1)>m)
                break;
            else
            {
               // cout<<i<<" "<<i+n-1<<" "<<juage(i,i+n-1)<<endl;
                if(juage(i,i+n-1)==ans)
                {
                    sc=i;break;
                }
            }
        }
        cout<<sc<<endl;
    }
}

 

转载于:https://www.cnblogs.com/huangdao/p/10526279.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值