hdu5685(乘法逆元)

hdu5685

题意:给定字符串,定义字符串哈希值的求法为:

H(s)=ilen(s)i=1(Si28) (mod 9973)

求从给定区间的子串的哈希值。


思路:暴力求法超时,可以预处理存下(0,i)间的哈希值Hash[i][。则Hash[a,b]=Hash[b]/Hash[a-1],

注意运用乘法逆元解决精度问题。

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<vector>
#include<climits>
#include<queue>
#include<set>
#include<list>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
const int maxn = 100000;
int Hash[maxn+1];
ll exgcd(ll a,ll b,ll &x,ll &y)// 扩展欧几里得
{
    if(b==0)
    {
        x=1;y=0;
        return a;
    }
    ll temp=exgcd(b,a%b,y,x);
    y-=x*(a/b);
    return temp;
}
ll finv(ll a,ll m)// 求逆元
{
    ll x,y;
    ll g=exgcd(a,m,x,y);
    x=(x%m+m)%m;//
    return x;
}
int main()
{
    int n;
    int a,b;
    string s;
    while(cin>>n)
    {
        cin>>s;
        Hash[0]=1;
        for(int i=0;i<s.length();i++)
        Hash[i+1]=Hash[i]*(s[i]-28)%9973;
        while(n--)
        {
            cin>>a>>b;
            a=Hash[a-1];
            b=Hash[b];
            int temp=finv(a,9973);
            int ans=(b*temp)%9973;
            printf("%d\n",ans);
        }
    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值