Take POJ 1743 as an example. The cardinality sort in the template is based on the forward star.
The specific proof process is described in the algorithm collection of "suffix array-a powerful tool to deal with strings," a very good article.
#include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include < cstdio> #include <queue> #include <cmath> #include <stack> #include <map> #include <ctime > #include <iomanip> #pragma comment (linker, "/stack:1024000000"); #define EPS (1e-6) #define LL Long Long#define ULL unsigned long long#define _ll __int64#define INF 0x3f3f3f3f#define Mod 1000000007using namespace Std;const int maxn = 20510;int s[maxn];int rank[2*maxn],sa[2*maxn],tr[2*maxn],high[maxn];struct n{int v,next;} Edge[2*maxn];int tail[maxn],top;inline void Link (int u,int v) {edge[top].v = v; Edge[top].next =-1; Edge[tail[u]].next = Top; Tail[u] = top++;} void Get_sa (int *s,int n) {memset (rank,0,sizeof (Rank)); memset (sa,0,sizeof (SA)); int i,j,k,ans,site; for (i = max (n,200); I >= 0; i) tail[i] = I,edge[i].next =-1; Top = max (n,200) +1; for (i = 1; I <= n; ++i) Link (s[i],i); Ans = 1,site = 1;for (i = 0; I <=, ++i) {for (j = edge[i].next; J! =-1; j = edge[j].next) sa[site++] = Edge[j]. V,RANK[EDGE[J].V] = ans; if (edge[i].next! =-1) ans++; Tail[i] = I,edge[i].next =-1; } for (k = 1;k <= n; k <<= 1) {Top = n+1; for (i = 1;i <= n; ++i) Link (Rank[sa[i]+k],sa[i]); site = 1; for (i = 0;i <= N, ++i) {for (j = edge[i].next;j! = 1; j = edge[j].next) sa[site++] = EDGE[J].V; Tail[i] = I,edge[i].next =-1; } Top = n+1; for (i = 1;i <= n; ++i) Link (Rank[sa[i]],sa[i]); site = 1; for (i = 1;i <= N, ++i) {for (j = edge[i].next;j! = 1; j = edge[j].next) sa[site++] = EDGE[J].V; Tail[i] = I,edge[i].next =-1; } for (tr[sa[1]] = 1,i = 2,ans = 1;i <= n; ++i) {if (Rank[sa[i]]! = rank[sa[i-1] | | | RANK[SA[I]+K]! = RANK[SA[I-1]+K]) ans++; Tr[sa[i]] = ans; } for (i = 1;i <= n; ++i) rank[i] = Tr[i]; if (ans >= n) break; } for (i = 1,k = 1;i <= n; ++i) {if (k) k--; if (rank[i] = = 1) {k = 0;high[1] = n-sa[1]+1;continue;} j = Sa[rank[i]-1]; while (i+k <= n && j+k <= n && s[i+k] = = S[j+k]) k++; High[rank[i]] = k; }////for (i = 1;i <= n; ++i)//printf ("i =%2d SA =%2d Rank =%2d High =%2d\n", i,sa[i],rank[i],high[i]); The above is the construction process for Rank,sa,high}bool Check (int mid,int n) {int L = Sa[1],r = Sa[1],i; for (i = 2;i <= n; ++i) {if (High[i] >= mid) {L = min (sa[i],l), R = max (sa[i],r); if (L+mid < R) return true; } else L = Sa[i],r = Sa[i]; } return false;} int main () {int i,n; while (scanf ("%d", &n) && N) {for (i = 1;i <= n; ++i) scanf ("%d", &s[i]); for (i = N;i >= 2; i.) s[i]-= s[i-1]-100; Get_sa (S,n); int mid,anw = 0,low = 1,high = N; while (low <= high) {mid = (low + high) >>1; if (Check (mid,n)) ANW = max (anw,mid), low = mid+1; else high = mid-1; } printf ("%d\n", anw+1 < 5 0:anw+1); } return 0;}
Initial suffix array