本文共 1525 字,大约阅读时间需要 5 分钟。
为了解决这个问题,我们需要判断两个子串是否是等价的。具体来说,给定一个母串和多个查询,每个查询询问两个子串是否可以一一对应。我们可以使用滚动哈希技术来高效地解决这个问题。
#include#include #include #include using namespace std;#define ll long longconst int N = 2 * 100000 + 10;const int base = 131;const int mod = 19260817;int n, m;string s;ll p[N], h[N];int main() { scanf("%d %d", &n, &m); scanf("%s", s.c_str()); p[0] = 1; for (int i = 1; i <= n; ++i) { p[i] = (p[i-1] * base) % mod; } for (int i = 1; i <= n; ++i) { ll val = (s[i-1] - 'a' + 1); h[i] = (h[i-1] * base + val) % mod; } for (int i = 0; i < m; ++i) { int x, y, len; scanf("%d %d %d", &x, &y, &len); if (x + len - 1 > n || y + len - 1 > n) { printf("NO"); continue; } ll hash_a = (h[x + len - 1] - (h[x - 1] * p[len]) % mod) % mod; if (hash_a < 0) hash_a += mod; ll hash_b = (h[y + len - 1] - (h[y - 1] * p[len]) % mod) % mod; if (hash_b < 0) hash_b += mod; if (hash_a == hash_b) { printf("YES"); } else { printf("NO"); } } return 0;}
p和前缀哈希数组h。p数组存储了底数的幂次模运算结果,h数组存储了母串前缀哈希值。这种方法的时间复杂度为O(n)预处理和O(m)查询,能够高效处理大规模输入。
转载地址:http://cjor.baihongyu.com/