hdu 3518
題意:找出一個字符串中至少重復出現兩次的字串的個數,注意重復出現時不能有重疊的現象
解題思路:height[i]表示排名第i的后綴與排名第i-1的后綴的最長公共前綴,然后我們可以枚舉長度為k(1<=k<=len/2)的滿足要求的子串個數。
AC:
#include<iostream> #include<cstdio> #include<cstring> #include<set> #include<string> using namespace std;const int maxn = 1005; int s[maxn],t[maxn],t2[maxn],c[maxn]; int rk[maxn],sa[maxn],height[maxn]; char str[maxn];void getsa(int n,int m) {int i,*x = t,*y = t2,*t;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 = 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];t = y, y = x, x = t;p = 1, x[sa[0]] = 0;for(i = 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;} }void getheight(int n) {int i,j,k = 0;for(i = 1; i <= n; i++) rk[sa[i]] = i;for(i = 0; i < n; i++){if(k) k--;j = sa[rk[i]-1];while(s[i+k] == s[j+k]) k++;height[rk[i]] = k;} }int main() { while(cin>>str){if(str[0] == '#') break;int n = 0;for(int i = 0; str[i] != '\0'; i++)s[n++] = str[i];s[n] = 0;getsa(n+1,300);getheight(n);int ans = 0;for(int i=1; i<=(n+1)/2; i++) { int mint=1001; int maxt=-1; for(int j=1; j<=n; j++) { // 和j相鄰的公共前綴的最大長度。 if(height[j]>=i) { //n個后綴從小到大進行排序之后,把排好 //序的后綴的開頭位置順次放入sa[]中。 int tem=sa[j-1]>sa[j]?sa[j]:sa[j-1]; mint=mint>tem?tem:mint; tem=sa[j-1]>sa[j]?sa[j-1]:sa[j]; maxt=maxt>tem?maxt:tem; } else { if(mint+i<=maxt)ans++;//避免重疊。 mint=1001,maxt=-1; } } if(mint+i<=maxt)ans++; } cout<<ans<<endl;}return 0; }
總結
- 上一篇: 七步从Angular.JS菜鸟到专家(3
- 下一篇: 建立和使用Maven项目骨架Archet