ZCMU 2155 字符串HASH

本文介绍了一种使用字符串HASH解决区间字符串比较问题的方法。通过预先计算字符串的HASH值及其前缀乘积,可以在常数时间内查询任意指定区间的HASH值,进而判断两个区间内的字符串是否相等。

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

题目链接

题意:

给一个长度为n的字符串,有q次询问。每次询问查询给定区间[l1,r1]和[l2,r2]的字符串是否相等。是输出YES,否则输出NO。

思路:

字符串HASH。

C++代码:

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn = 1000010;
const int mod1 = 1e9+7;
const int mod2 = 1e9+9;
const int base1 = 131;
const int base2 = 233;

struct My_Hash
{
    ull Hash1[maxn],p1[maxn];
    ull Hash2[maxn],p2[maxn];

    void Insert( char s[] )
    {
        int len = strlen(s+1);
        Hash1[0] = 0,p1[0] = 1;
        Hash2[0] = 0,p2[0] = 1;
        for ( int i=1 ; i<=len ; i++ )
        {
            p1[i] = p1[i-1]*base1%mod1;
            p2[i] = p2[i-1]*base2%mod2;
            Hash1[i] = (Hash1[i-1]*base1%mod1+(ull)s[i])%mod1;
            Hash2[i] = (Hash2[i-1]*base2%mod2+(ull)s[i])%mod2;
        }
    }
    pair<ull,ull> GetHash( int l , int r )
    {
        ull tmp1 = ( Hash1[r]-p1[r-l+1]*Hash1[l-1]%mod1+mod1 )%mod1;
        ull tmp2 = ( Hash2[r]-p2[r-l+1]*Hash2[l-1]%mod2+mod2 )%mod2;
        return make_pair( tmp1 , tmp2 );
    }
}S;

int n,q,l1,r1,l2,r2;
char s[maxn];

int main()
{
    while( scanf ( "%d%d" , &n , &q )==2 )
    {
        scanf ( "%s" , s+1 );
        S.Insert(s);
        while( q-- )
        {
            scanf ( "%d%d%d%d" , &l1 , &r1 , &l2 , &r2 );
            pair<ull,ull>t1 = S.GetHash( l1 , r1 );
            pair<ull,ull>t2 = S.GetHash( l2 , r2 );
            printf ( "%s\n" , (t1.first==t2.first&&t1.second==t2.second)?"YES":"NO" );
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值