标签:
题意:给定长度为n(n <= 1000)的只含小写字母的字符串,问字符串子串不重叠出现最少两次的不同子串个数;
input:
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 1007; char s[MAXN]; int sa[MAXN],t[MAXN],t2[MAXN],c[MAXN],n; void build_sa(int m,int n) // m为字符ASCII码的最大值+1;n = strlen(s) + 1; { int i,*x = t, *y = t2; for(i = 0;i < m; i++) c[i] = 0; for(i = 0;i < n; i++) c[x[i] = s[i]]++; for(i = 1;i < m; i++) c[i] += c[i-1]; for(i = n - 1;i >= 0; i--) sa[--c[x[i]]] = i; for(int k = 1;k <= n;k <<= 1){ int p = 0; for(i = n - k;i < n;i++) y[p++] = i; for(i = 0;i < n;i++) if(sa[i] >= k) y[p++] = sa[i] - k; for(i = 0;i < m;i++) c[i] = 0; for(i = 0;i < n;i++) c[x[y[i]]]++; for(i = 1;i < m;i++) c[i] += c[i-1]; for(i = n - 1;i >= 0;i--) sa[--c[x[y[i]]]] = y[i]; swap(x,y); x[sa[0]] = 0;// 将字符彻底转变为序号; for(i = 1,p = 1;i < n;i++) x[sa[i]] = y[sa[i]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k]?p-1:p++; if(p >= n) break; m = p; } } int rk[MAXN],height[MAXN]; void getHeight() { int i,j,k = 0; for(i = 1;i <= n;i++) rk[sa[i]] = i; // rk[i]:后缀i在sa[]中的下标,从1开始 for(i = 0;i < n;i++){ if(k) k--; if(rk[i] == 0) continue; j = sa[rk[i] - 1]; while(i+k<n && j+k<n && s[i+k] == s[j+k]) k++; height[rk[i]] = k; // h[i] = height[rk[i]]; h[i] >= h[i-1] - 1; } } int main() { while(scanf("%s",s) == 1 && s[0] != ‘#‘){ ll ans = 0; n = strlen(s); s[n] = ‘#‘; build_sa(‘z‘+1,n+1); getHeight(); for(int i = 1;i <= n/2; i++){ int l = n+1,r = -1; for(int j = 2;j <= n;j++){ if(height[j] >= i){// 递推出最左最优的l,r; r = max(r,max(sa[j],sa[j-1])); l = min(l,min(sa[j],sa[j-1])); } else{ if(r-l >= i) ans++; r = -1,l = n+1; } } if(r-l >= i) ans++; } printf("%I64d\n",ans); } return 0; }
hdu 3518 Boring counting 后缀数组LCP
标签:
原文地址:http://www.cnblogs.com/hxer/p/5376537.html