题目大意
给出一个01串,要求按照字典序输出在串中出现两次以上的子串的出现次数。
题解
我是在hzwer学长的后缀数组专题中看到这道题的,但是我并没有很理解黄学长的暴力是怎么思考的…于是我在另一个地方得到了另一种思路。
首先要知道字串的性质:一个串的所有字串都可以表示为这个串某个后缀的某个前缀。换句话说,就是一个串的所有后缀的所有前缀都与这个串的子串一一对应。利用这个性质,这道题就可以写得很简短。
所以,这道题就转化为了求一个串的所有后缀的所有出现次数大于1的前缀出现的次数。这个问题显然可以把所有的后缀都插入在一个trie树上,那每一个点被经过的次数就是这个结点所表示的字串的出现的次数。
题目要求按字典序输出,因为是在trie树上,所以按先序遍历序输出就是按字典序输出答案了。
代码
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn=int(3e3)+11;
int n,s[maxn];
char ch[maxn];
int to[maxn*maxn][2], cnt[maxn*maxn], tot=0;
void Insert(int st) {
int now=0;
for(int i=st;i<=n;i++) {
if(!to[now][s[i]]) to[now][s[i]]=++tot;
now=to[now][s[i]];
cnt[now]++;
}
return;
}
void Get(int now) {
if(now && cnt[now]>1) printf("%d\n",cnt[now]);
if(to[now][0]) Get(to[now][0]);
if(to[now][1]) Get(to[now][1]);
return;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif // ONLINE_JUDGE
scanf("%d%s",&n,ch+1);
for(int i=1;i<=n;i++)
s[i]=ch[i]-'0';
for(int i=1;i<=n;i++)
Insert(i);
Get(0);
return 0;
}