I am getting time limit exceeded for 3 test cases. I used rolling hash for solving this. Any suggestions fot optimizing it?
Thank You.
https://cses.fi/problemset/task/2102/
My Solution
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int mod = 1000000007;
class RollHash{
public:
int Hash[1000005];
RollHash(){
memset(Hash,0,sizeof Hash);
}
void fillRoll(string s)
{
int n = s.length();
int x = 131;
for(int i=0;i<n;i++)
{
Hash[i+1] = (Hash[i] + x*(s[i]-'a'+1))%mod;
x*=131;
x%=mod;
}
}
int power(int a,int b)
{
if(b == 0)return 1;
int ans = 1;
while(b > 0)
{
if(b%2)
ans = (ans*a)%mod;
a = (a*a)%mod;
b/=2;
}
return ans;
}
int get(int l,int r)
{
return ((Hash[r] - Hash[l-1] + mod)*power(power(131,l-1),mod-2))%mod;
}
};
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string word;
cin >> word;
int n = word.length();
RollHash r;
r.fillRoll(word);
int m;
cin >> m;
while(m--)
{
int flag = 0;
string s;
cin >> s;
int hash = 0;
int x = 131;
for(int i=0;i<s.length();i++)
{
hash = (hash + x*(s[i]-'a'+1))%mod;
x*=131;
x%=mod;
}
for(int i=1;i+s.length()-1<=n;i++)
{
int x = i;
int y = i + s.length() - 1;
if(r.get(x,y) == hash)
{
flag = 1;
break;
}
}
if(flag)cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}
I solved this question and counting pattern question using binary search on suffix array of string.
Can you explain in short about your approach?
https://cses.fi/paste/1ca4a1d5de2666002569a5/
You can refer my code for finding first position of pattern, it has solution for all the three questions finding pattern, counting pattern, and first position, In counting pattern and finding pattern segtree is not needed, only binary search will work.
there are at most $$$sqrt(5⋅10^5)$$$ different sizes of strings.
so create a hash for each size of the strings given in the input and save it into a map
This is stll giving TLE, is it possible for you to share your code.
You can use a suffix automaton rather than hashing for a deterministic solution.