卡map还行.....手写hash表即可。
我一开始以为这个k会变......在sam上想各种奇技淫巧。
k不变就是问一段区间有多少对长度为k的子串相同。
然后hash把子串转化为数字,就是区间有多少对相同数字。直接莫队即可。
#include <bits/stdc++.h> inline void read(int &x) {
x = ;
char c = getchar();
while(c < '' || c > '') c = getchar();
while(c >= '' && c <= '') {
x = x * + c - ;
c = getchar();
}
return;
} typedef long long LL;
typedef unsigned long long uLL;
const int N = ;
const uLL B = ; uLL h[N], pw[N];
std::map<uLL, int> mp;
int n, k, val[N], fr[N], bin[N];
char str[N];
LL ans[N], Ans; namespace Map {
const int mod = ;
struct Edge {
uLL val;
int num, nex;
}edge[N]; int tp;
int e[mod], num;
inline int insert(uLL v) {
int x = v % mod;
for(int i = e[x]; i; i = edge[i].nex) {
if(edge[i].val == v) return edge[i].num;
}
edge[++tp].val = v;
edge[tp].num = ++num;
edge[tp].nex = e[x];
e[x] = tp;
return num;
}
} struct Ask {
int l, r, id;
inline bool operator <(const Ask &w) const {
if(fr[l] != fr[w.l]) return l < w.l;
return r < w.r;
}
}ask[N]; inline uLL Hash(int l, int r) {
return h[r] - h[l - ] * pw[r - l + ];
} inline void getHash() {
pw[] = ;
for(register int i = ; i <= n; i++) {
pw[i] = B * pw[i - ];
h[i] = h[i - ] * B + str[i];
}
for(register int i = ; i + k - <= n; i++) {
uLL t = Hash(i, i + k - );
//printf("i = %d t = %llu \n", i, t);
val[i] = Map::insert(t);
//printf("val %d = %d \n", i, val[i]);
}
return;
} inline void add(int x) {
Ans += bin[val[x]];
bin[val[x]]++;
return;
} inline void del(int x) {
bin[val[x]]--;
Ans -= bin[val[x]];
return;
} int main() {
int m;
read(n); read(m); read(k);
scanf("%s", str + );
int T = (double)n / sqrt(m);
for(register int i = ; i <= m; i++) {
read(ask[i].l); read(ask[i].r);
ask[i].r = std::min(ask[i].r, n - k + );
ask[i].id = i;
}
for(register int i = ; i <= n; i++) fr[i] = (i - ) / T + ;
std::sort(ask + , ask + m + );
getHash(); int l = , r = ; bin[val[]] = ;
for(register int i = ; i <= m; i++) {
if(ask[i].l >= ask[i].r) {
ans[ask[i].id] = ;
continue;
}
while(ask[i].l < l) {
add(--l);
}
while(r < ask[i].r) {
add(++r);
}
while(l < ask[i].l) {
del(l++);
}
while(ask[i].r < r) {
del(r--);
}
ans[ask[i].id] = Ans;
}
for(register int i = ; i <= m; i++) printf("%lld\n", ans[i]);
return ;
}
AC代码