hdu 3518 Boring counting 后缀数组

时间:2021-09-17 14:54:21

题目链接

根据height数组的性质分组计算。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
const int maxn = 2e4+;
int sa[maxn];
int t1[maxn],t2[maxn],c[maxn], a[maxn];
int rankk[maxn],height[maxn], ans;
void build_sa(int s[],int n,int m)
{
int i,j,p,*x=t1,*y=t2;
for(i=;i<m;i++)c[i]=;
for(i=;i<n;i++)c[x[i]=s[i]]++;
for(i=;i<m;i++)c[i]+=c[i-];
for(i=n-;i>=;i--)sa[--c[x[i]]]=i;
for(j=;j<=n;j<<=)
{
p=;
for(i=n-j;i<n;i++)y[p++]=i;
for(i=;i<n;i++)if(sa[i]>=j)y[p++]=sa[i]-j;
for(i=;i<m;i++)c[i]=;
for(i=;i<n;i++)c[x[y[i]]]++;
for(i=;i<m;i++)c[i]+=c[i-];
for(i=n-;i>=;i--)sa[--c[x[y[i]]]]=y[i];
swap(x,y);
p=;x[sa[]]=;
for(i=;i<n;i++)
x[sa[i]]=y[sa[i-]]==y[sa[i]] && y[sa[i-]+j]==y[sa[i]+j]?p-:p++;
if(p>=n)break;
m=p;
}
}
void getHeight(int s[],int n)
{
int i,j,k=;
for(i=;i<=n;i++)rankk[sa[i]]=i;
for(i=;i<n;i++)
{
if(k)k--;
j=sa[rankk[i]-];
while(s[i+k]==s[j+k])k++;
height[rankk[i]]=k;
}
}
int cal(int x, int n) {
int minn = sa[], maxx = sa[];
int flag = ;
for(int i = ; i<=n; i++) {
if(height[i]<x) {
if(maxx-minn>=x)
ans++;
maxx = minn = sa[i];
flag = ;
} else {
maxx = max(maxx, sa[i]);
minn = min(minn, sa[i]);
}
}
if(maxx-minn>=x)
ans++, flag = ;
return flag;
}
int main()
{
string s;
while(cin>>s) {
if(s[] == '#')
break;
ans = ;
for(int i = ; i<s.size(); i++)
a[i] = s[i]-'a'+;
a[s.size()] = ;
build_sa(a, s.size()+, );
getHeight(a, s.size());
for(int i = ; i<=(s.size()+)/; i++) {
if(!cal(i, s.size()))
break;
}
cout<<ans<<endl;
}
return ;
}