题意:
给一个长度为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;
}