![]() | ||||||||||
| ||||||||||
ReincarnationTime Limit: 6000/3000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 2233 Accepted Submission(s): 780
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
Sample Output
|
题意:查询区间(l,r)内,不同的子串个数
思路:先用O(n^2)的方式预处理出来所有区间的不同子串的数量,然后直接查询就行了。原来后缀数组也写过,都忘了怎么写的了,不过SAM比后缀数组好写多了
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=2010;
const int SIGMA_SIZE=26;
char s[maxn];
int ans[maxn][maxn];
int Q;
struct SAM_Node
{
SAM_Node *par,*next[SIGMA_SIZE];
int len,id,pos;
SAM_Node(){}
SAM_Node(int _len)
{
par=0;
len=_len;
memset(next,0,sizeof(next));
}
};
SAM_Node node[maxn*2],*root,*last;
int SAM_size;
SAM_Node *newSAM_Node(int len)
{
node[SAM_size]=SAM_Node(len);
node[SAM_size].id=SAM_size;
return &node[SAM_size++];
}
SAM_Node *newSAM_Node(SAM_Node *p)
{
node[SAM_size]=*p;
node[SAM_size].id=SAM_size;
return &node[SAM_size++];
}
void SAM_init()
{
SAM_size=0;
root=last=newSAM_Node(0);
node[0].pos=0;
}
void SAM_add(int x,int len)
{
SAM_Node *p=last,*np=newSAM_Node(p->len+1);
np->pos=len;
last=np;
while(p&&!p->next[x])
{
p->next[x]=np;
p=p->par;
}
if(!p)
{
np->par=root;
return ;
}
SAM_Node *q=p->next[x];
if(q->len==p->len+1)
{
np->par=q;
return ;
}
SAM_Node *nq=newSAM_Node(q);
nq->len=p->len+1;
q->par=nq;
np->par=nq;
while(p&&p->next[x]==q)
{
p->next[x]=nq;
p=p->par;
}
}
void SAM_build(char *s)
{
SAM_init();
int len=strlen(s);
for(int i=0;i<len;i++)
SAM_add(s[i]-'a',i+1);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
int len=strlen(s);
memset(ans,0,sizeof(ans));
for(int i=0;i<len;i++)
{
SAM_init();
for(int j=i;j<len;j++)
SAM_add(s[j]-'a',j-i+1);
for(int j=1;j<SAM_size;j++)
ans[i][node[j].pos+i-1]+=node[j].len-node[j].par->len;
for(int j=i+1;j<len;j++)
ans[i][j]+=ans[i][j-1];
}
scanf("%d",&Q);
while(Q--)
{
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",ans[l-1][r-1]);
}
}
return 0;
}