字符串哈希
【用法】
将字符串的所有前缀表示为一个哈希值。
先设置成一个p进制 ( 一般取131 或者 13331 ) , 哈希值R为2^64 次 ( 或者开 unsigned longlong 当做取模了)
【作用】
判断字符串的子串是否相等。
【代码】
#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include <cmath> #include <set> #define ms(a, b) memset(a,b,sizeof(a)) #define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define ll long long #define ull unsigned long long #define rep(i, a, b) for(ll i=a;i<=b;i++) #define lep(i, a, b) for(ll i=a;i>=b;i--) #define endl '\n' #define pii pair<int, int> #define pll pair<ll, ll> #define vi vector<ll> #define vpi vector<pii> #define vpl vector<pll> #define mi map<ll,ll> #define all(a) (a).begin(),(a).end() #define gcd __gcd #define pb push_back #define mp make_pair #define lb lower_bound #define ub upper_bound #define ff first #define ss second #define test4(x, y, z, a) cout<<"x is "<<x<<" y is "<<y<<" z is "<<z<<" a is "<<a<<endl; #define test3(x, y, z) cout<<"x is "<<x<<" y is "<<y<<" z is "<<z<<endl; #define test2(x, y) cout<<"x is "<<x<<" y is "<<y<<endl; #define test1(x) cout<<"x is "<<x<<endl; using namespace std; const int N = 100010; const int maxx = 0x3f3f3f; const int mod = 1e9 + 7; const int minn = -0x3f3f3f; const int M = 2 * N; const int P = 131 ; ll T, n, m; char s[N]; unsigned ll h[N],p[N]; unsigned ll getsr(int x,int y ){ return h[y]-h[x-1]*p[y-x+1]; } void solve() { cin>>n>>m; cin>>s+1; p[0] = 1 ; rep(i,1,n){ h[i] = h[i-1] * P + s[i]; p[i] = p[i-1] * P ; } while ( m-- ){ int l1,l2,r1,r2; cin>>l1>>r1>>l2>>r2; if ( getsr(l1,r1) == getsr(l2,r2) ) cout<<"Yes"<<endl; else cout<<"No"<<endl; } } int main() { fast; solve(); return 0; }
【题目连接】

浙公网安备 33010602011771号