SPOJ - DISUBSTR Distinct Substrings

来源:互联网 发布:淘宝上代购dw手表600 编辑:程序博客网 时间:2024/06/09 20:50

1.题面

http://www.spoj.com/problems/DISUBSTR/en/

2.题意

问一个字符串中有多少个不同的子串

3.思路

参考《后缀数组 罗穗蹇》中的思路,很好写

4.代码

/*****************************************************************    > File Name: Cpp_Acm.cpp    > Author: Uncle_Sugar    > Mail: uncle_sugar@qq.com    > Created Time: 2016年07月29日 星期五 20时13分08秒*****************************************************************/# include <cstdio># include <cstring># include <cctype># include <cmath># include <cstdlib># include <climits># include <iostream># include <iomanip># include <set># include <map># include <vector># include <stack># include <queue># include <algorithm>using namespace std;struct QuickIO{QuickIO(){const int SZ = 1<<20;setvbuf(stdin ,new char[SZ],_IOFBF,SZ);setvbuf(stdout,new char[SZ],_IOFBF,SZ);}//*From programcaicai*//}QIO;template<class T>void PrintArray(T* first,T* last,char delim=' '){ for (;first!=last;first++) cout << *first << (first+1==last?'\n':delim); }const int debug = 1;const int size  = 10 + 200000 ; const int INF = INT_MAX>>1;typedef long long ll;const int MAXN = 2*100000+10;int t1[MAXN],t2[MAXN],c[MAXN];bool cmp(int *r,int a,int b,int l){return r[a]==r[b]&&r[a+l]==r[b+l];}void da(char str[],int sa[],int rrank[],int height[],int n,int m){n++;int i, j, p, *x = t1, *y = t2;for (i = 0;i < m;i++) c[i] = 0;for (i = 0;i < n;i++) c[x[i] = str[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 (j = 1;j <= n; j<<= 1){p = 0;for (i = n-j; i < n; i++)y[p++] = i;for (i = 0; i < n; i++)if (sa[i] >= j) y[p++] = sa[i] - j; 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);p = 1; x[sa[0]] = 0;for (i = 1; i < n; i++){x[sa[i]] = cmp(y,sa[i-1],sa[i],j)?p-1:p++;}if ( p>=n ) break;m = p;}int k = 0;n--;for (i = 0; i<= n; i++) rrank[sa[i]] = i;for (i = 0; i< n; i++){if (k) k--;j = sa[rrank[i]-1];while (str[i+k] == str[j+k]){k++;}height[rrank[i]] = k;}}int rrank[MAXN],height[MAXN];int sa[MAXN];char str[size];int main(){std::ios::sync_with_stdio(false);cin.tie(0);int i,j;int T;cin >> T;while (T--){cin >> str;int len = strlen(str); //# void da(char str[],int sa[],int rrank[],int height[],int n,int m){da(str,sa,rrank,height,len,128);//# for (i=1;i<=len;i++){//# cout << "*" << i << "* ";//# PrintArray(str+sa[i],str+len);//# }//# cout << endl;ll ans = len - sa[1];//# cout << "ans = " << ans << endl;for (i=2;i<=len;i++){ans += len - sa[i] - height[i];}cout << ans << endl;}return 0;}


0 0