题目链接
题意:给出一个字符串,问区间的不同子串有几个
首先可以直接预处理出所有长度的字串的hash值,然后用区间dp维护。
区间dp的时候需要记录同一长度下的上一个相同hash值出现的位置,使用STL 的map会超时,所以需要手动写个hashMap,也就是hash加冲突处理。记录相同的hash上一次的位置
//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<set>
#include<map>
#include<string>
#include<cassert>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define fastIO ios::sync_with_stdio(false);cin.tie(0);
#define ll unsigned long long
#define pb push_back
#define gcd __gcd
#define For(i,j,k) for(int i=(j);i<=k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)
typedef vector<ll> vec;
typedef pair<int,int> PI;
const double EPS = 1e-8;
const int maxn = 2e3+100;
const int inf = 1 << 28;
char str[maxn];
ll pp[maxn],p=237,s[maxn];
int dp[maxn][maxn];
const int N=10007;
struct HashMap{
int head[N],next[N],tot;
ll value[N];
int f[N];
void init(){
tot=0;
memset(head,-1,sizeof(head));
}
int insert(ll val,int id){
int t=val%N;
for(int i=head[t];~i;i=next[i]){
if(val==value[i]){
int tmp=f[i];
f[i]=id;
return tmp;
}
}
f[tot]=id;
value[tot]=val;
next[tot]=head[t];
head[t]=tot++;
return 0;
}
}H;
int main(){
pp[0]=1;
for(int i=1;i<maxn;i++)pp[i]=pp[i-1]*p;
int T;scanf("%d",&T);
while(T--){
scanf("%s",str+1);
int len=strlen(str+1);
s[0]=0;
for(int i=1;i<=len;i++)s[i]=s[i-1]*p+str[i];
cl(dp,0);
for(int L=1;L<=len;L++){
H.init();
for(int i=1;i+L-1<=len;i++){
ll t=s[i+L-1]-s[i-1]*pp[L];
int x=H.insert(t,i);
dp[i][i+L-1]++;
dp[x][i+L-1]--;
}
}
for(int i=len;i>=0;i--)
for(int j=i;j<=len;j++)
dp[i][j]+=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
int q;scanf("%d",&q);
while(q--){
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",dp[x][y]);
}
}
return 0;
}