hdu4622
Problem Description
Now you are back,and have a task to do:
Given you a string s consist of lower-case English letters only,denote f(s) as the number of distinct sub-string of s.
And you have some query,each time you should calculate f(s[l…r]), s[l…r] means the sub-string of s start from l end at r.
Input
The first line contains integer T(1<=T<=5), denote the number of the test cases.
For each test cases,the first line contains a string s(1 <= length of s <= 2000).
Denote the length of s by n.
The second line contains an integer Q(1 <= Q <= 10000),denote the number of queries.
Then Q lines follows,each lines contains two integer l, r(1 <= l <= r <= n), denote a query.
Output
For each test cases,for each query,print the answer in one line.
Sample Input
2
bbaba
5
3 4
2 2
2 5
2 4
1 4
baaba
5
3 3
3 4
1 4
3 5
5 5
Sample Output
3
1
7
5
8
1
3
8
5
1
画出head,next,state,f表格
state存储每一次的val,若相同则改变next的值使得next!=-1访问下一个节点,head指向next的下标,f存储开始的位置下标
#include<stdio.h> //by kuangbin加了
#include<string.h>
#include<stdlib.h>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
const int HASH = 10007;
const int MAXN = 2100;
struct hashmap {
int head[HASH],next[MAXN],size;
unsigned long long state[MAXN];
int f[MAXN];
void init() {
size=0;
memset(head,-1,sizeof(head));
}
int insert(unsigned long long val,int _id) { //"a,b"和"b,a"的hash值不一样!!!!!
int h=val%HASH;
for(int i=head[h]; i!=-1; i=next[i]) {
if(val==state[i]) {
int temp=f[i];
f[i]=_id;
return temp;
}
}
f[size]=_id; //f[i]i位置放的是开始位置
state[size]=val; //state
next[size]=head[h]; //next存放-1,有数据的点
head[h]=size++; //head
return 0;
}
} h;
const int seed = 13331;
unsigned long long P[MAXN];
unsigned long long S[MAXN];
char str[MAXN];
int ans[MAXN][MAXN];
int main() {
freopen("1.txt","w",stdout);
P[0]=1;
for(int i=1; i<MAXN; i++)
P[i]=P[i-1]*seed; //预先处理hash^(r-l+1)
int T;
scanf("%d",&T);
while(T--) {
scanf("%s",str);
int n=strlen(str);
for(int i=1; i<=n; i++)
S[i]=S[i-1]*seed+str[i-1]; //hash值
memset(ans,0,sizeof(ans)); //二维dp
for(int L=1; L<=n; L++) { //L表示长度
h.init();
for(int i=1; i+L-1<=n; i++) { //i表示开始位置
int l=h.insert(S[i+L-1]-S[i-1]*P[L],i);
ans[i][i+L-1]++;
ans[l][i+L-1]--;
}
}
for(int i=n; i>=0; i--)
for(int j=i; j<=n; j++)
ans[i][j]+=ans[i+1][j]+ans[i][j-1]-ans[i+1][j-1];
h.out();
int Q;
scanf("%d",&Q);
while(Q--) {
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",ans[a][b]);
}
}
return 0;
}