HDU4622:区间查询不同子串个数
用后缀自动机预处理出所有区间的不同子串个数
建立n次后缀自动机
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std; const int CHAR = ;
const int MAXN = ;
struct SAM_Node
{
SAM_Node *fa,*next[CHAR];
int len;
int id,pos;
SAM_Node(){}
SAM_Node(int _len)
{
fa = ;
len = _len;
memset(next,,sizeof(next));
}
};
SAM_Node SAM_node[MAXN*], *SAM_root, *SAM_last;
int SAM_size;
SAM_Node *newSAM_Node(int len)
{
SAM_node[SAM_size] = SAM_Node(len);
SAM_node[SAM_size].id = SAM_size;
return &SAM_node[SAM_size++];
}
SAM_Node *newSAM_Node(SAM_Node *p)
{
SAM_node[SAM_size] = *p;
SAM_node[SAM_size].id = SAM_size;
return &SAM_node[SAM_size++];
}
void SAM_init()
{
SAM_size = ;
SAM_root = SAM_last = newSAM_Node();
SAM_node[].pos = ;
}
void SAM_add(int x,int len)
{
SAM_Node *p = SAM_last, *np = newSAM_Node(p->len+);
np->pos = len;
SAM_last = np;
for(;p && !p->next[x];p = p->fa)
p->next[x] = np;
if(!p)
{
np->fa = SAM_root;
return;
}
SAM_Node *q = p->next[x];
if(q->len == p->len + )
{
np->fa = q;
return;
}
SAM_Node *nq = newSAM_Node(q);
nq->len = p->len + ;
q->fa = nq;
np->fa = nq;
for(;p && p->next[x] == q;p = p->fa)
p->next[x] = nq;
}
void SAM_build(char *s)
{
SAM_init();
int len = strlen(s);
for(int i = ;i < len;i++)
SAM_add(s[i] - 'a',i+);
} int Q[MAXN][MAXN];
char str[MAXN];
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",str);
int n = strlen(str);
memset(Q,,sizeof(Q));
for(int i = ;i < n;i++)
{
SAM_init();
for(int j = i;j < n;j++)
{
SAM_add(str[j]-'a',j-i+);
}
for(int j = ;j < SAM_size;j++)
{
Q[i][SAM_node[j].pos-+i]+=SAM_node[j].len - SAM_node[j].fa->len;
}
for(int j = i+;j < n;j++)
Q[i][j] += Q[i][j-];
}
int M;
int u,v;
scanf("%d",&M);
while(M--)
{
scanf("%d%d",&u,&v);
u--;v--;
printf("%d\n",Q[u][v]);
}
}
return ;
}
此题也有字符串哈希做法
没看懂就不贴了