1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 3e5 + 5;
int n, k, q, blk;
string s;
vector<array<int, 26>> hs;
vector<pair<ll, ll>> hval;
vector<int> hid;
ll ans;
const ll M1 = 1e9 + 7;
const ll M2 = 1e9 + 9;
const ll B1 = 911;
const ll B2 = 3571;
pair<ll, ll> hsh(const array<int, 26>& a) {
ll h1 = 0, h2 = 0;
for (int i = 0; i < 26; ++i) {
h1 = (h1 * B1 + a[i]) % M1;
h2 = (h2 * B2 + a[i]) % M2;
}
return {h1, h2};
}
struct Q {
int l, r, id;
bool operator<(const Q &o) const {
int bl = l / blk, br = o.l / blk;
if (bl != br) return bl < br;
return (bl & 1) ? r < o.r : r > o.r;
}
};
vector<int> cnt;
void add(int x) {
int id = hid[x];
ans += cnt[id];
cnt[id]++;
}
void del(int x) {
int id = hid[x];
cnt[id]--;
ans -= cnt[id];
}
void run() {
cin >> n >> k >> q;
cin >> s;
s = " " + s;
blk = sqrt(n) + 1;
hs.resize(n + 1);
hs[0].fill(0);
for (int i = 1; i <= n; i++) {
hs[i] = hs[i - 1];
hs[i][s[i] - 'a'] = (hs[i][s[i] - 'a'] + 1) % k;
}
hval.resize(n + 1);
for (int i = 0; i <= n; i++) hval[i] = hsh(hs[i]);
vector<pair<ll, ll>> all = hval;
sort(all.begin(), all.end());
all.erase(unique(all.begin(), all.end()), all.end());
auto get = [&](pair<ll, ll> h) {
return lower_bound(all.begin(), all.end(), h) - all.begin();
};
hid.resize(n + 1);
for (int i = 0; i <= n; ++i) hid[i] = get(hval[i]);
vector<Q> qry(q);
for (int i = 0; i < q; ++i) {
int x, y;
cin >> x >> y;
qry[i] = {x - 1, y, i};
}
sort(qry.begin(), qry.end());
vector<ll> res(q);
cnt.assign(all.size(), 0);
int L = 0, R = -1;
ans = 0;
for (auto [l, r, id] : qry) {
while (R < r) add(++R);
while (R > r) del(R--);
while (L < l) del(L++);
while (L > l) add(--L);
res[id] = ans;
}
for (auto x : res) cout << x << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
run();
return 0;
}
|