**Test Instructions:** for the given string, output the number of substrings of different lengths

** Analysis: ** There is a fact that each substring must be a prefix of a suffix, in other words, each suffix of each prefix represents a substring, then how to find the prefix of so many substrings or suffixes of the different and count it? The idea is that all possible substrings-the number of substrings to repeat. First we easily get a string length of Len for Len * (len + 1)/2. How do you know how many substrings are duplicated? The answer is to use the suffix array to run through the height, get all the longest common prefixes (LCP), the values of these longest public prefixes exist in the height, for any two suffixes of the longest common prefix length is actually the number of repetitions of the substring, so long as you iterate through the height array, Subtract all Height values from the total number of substrings that have just been made.

#include <bits/stdc++.h>using namespacestd;Const intMAXN =50010;intSA[MAXN],S[MAXN],WA[MAXN], WB[MAXN], WS[MAXN], WV[MAXN];intRANK[MAXN], HEIGHT[MAXN];BOOLcmpintR[],intAintBintL) {returnR[a] = = R[b] && r[a+l] = = r[b+L]; }voidDaintR[],intSa[],intNintm) { intI, J, p, *x = wa, *y =WB; for(i =0; I < m; ++i) Ws[i] =0; for(i =0; I < n; ++i) ws[x[i]=r[i]]++; for(i =1; I < m; ++i) ws[i] + = ws[i-1]; for(i = n1; I >=0; -i) sa[--ws[x[i]] =i; for(j =1, p =1; P < n; J *=2, M =p) { for(P =0, 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 < n; ++i) Wv[i] =X[y[i]]; for(i =0; I < m; ++i) Ws[i] =0; for(i =0; I < n; ++i) ws[wv[i]]++; for(i =1; I < m; ++i) ws[i] + = ws[i-1]; for(i = n1; I >=0; -i) sa[--ws[wv[i]] =Y[i]; for(Std::swap (x, y), p =1, x[sa[0]] =0, i =1; I < n; ++i) x[sa[i]= CMP (y, sa[i-1], Sa[i], j)? P1: p++; }}voidCalheight (intR[],intSa[],intN) { intI, j, k =0; for(i =1; I <= N; ++i) Rank[sa[i] =i; for(i =0; I < n; height[rank[i++]] =k) for(k?k--:0, j = sa[rank[i]-1]; R[i+k] = = R[j+k]; k++);}CharSS[MAXN];intS[MAXN];intMainvoid){ intncase; scanf ("%d", &ncase); while(ncase--) {scanf ("%s", SS); intLen =strlen (SS); for(intI=0; i<len; i++) S[i] = (int) ss[i]; S[len]=0; Da (S, SA, Len+1, -); Calheight (S, SA, Len); Long LongTMP =Len; Long LongAns = (TMP * (tmp+1)) /2; for(intI=2; i<=len; i++) ans-= height[i];//or ans + = len-i-height[rank[i]];printf"%lld\n", ans); } return 0;}

View Code

Spoj 694 | | 705 Distinct substrings (suffix array && number of different substrings)