研究了很久,终于有自己的后缀数组模板了~~~~
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define LEN 256
void SuffixArray(char *str, int *rank, int *sa, int sz, int len) {
int v0, v1, v00, v01, p;
int *s = (int *)malloc(sz * sizeof(int));
int *tmp = (int *)malloc(len * sizeof(int));
for(int i = 0; i < sz; i++)
s[i] = 0;
for(int i = 0; i < len; i++)
s[rank[i] = str[i]]++;
for(int i = 1; i < sz; i++)
s[i] += s[i - 1];
for(int i = len - 1; i >= 0; i--)
sa[--s[rank[i]]] = i;
for(int j = 1; j < len; j <<= 1) {
p = 0;
for(int i = len - j; i < len; i++)
tmp[p++] = i;
for(int i = 0; i < len; i++) {
if(sa[i] >= j)
tmp[p++] = sa[i] - j;
}
for(int i = 0; i < sz; i++)
s[i] = 0;
for(int i = 0; i < len; i++)
s[rank[i]]++;
for(int i = 1; i < sz; i++)
s[i] += s[i - 1];
for(int i = len - 1; i >= 0; i--)
sa[--s[rank[tmp[i]]]] = tmp[i];
tmp[sa[0]] = p = 0;
for(int i = 1; i < len; i++) {
v0 = sa[i - 1];
v1 = sa[i];
if(v0 + j < len)
v00 = rank[v0 + j];
else
v00 = -1;
if(v1 + j < len)
v01 = rank[v1 + j];
else
v01 = -1;
if(rank[v0] == rank[v1] && v00 == v01)
tmp[sa[i]] = p;
else
tmp[sa[i]] = ++p;
}
for(int i = 0; i < len; i++)
rank[i] = tmp[i];
sz = ++p;
}
}
void Height(char *str, int *rank, int *sa, int *height, int len) {
height[0] = 0;
for(int i = 0, j = 0; i < len; i++) {
if(rank[i] == 0)
continue;
for(; str[i + j] == str[sa[rank[i] - 1] + j]; j++);
height[rank[i]] = j;
if(j > 0)
j--;
}
}
int main() {
char str[] = "banana";
int len = strlen(str);
int sz = LEN;
int *rank = (int *)malloc(sz * sizeof(int));
int *sa = (int *)malloc(len * sizeof(int));
int *height = (int *)malloc(len * sizeof(int));
SuffixArray(str, rank, sa, sz, len);
Height(str, rank, sa, height, len);
printf("Rank:\n");
for(int i = 0; i < len; i++)
printf("%d ", rank[i]);
printf("\n");
printf("Sa:\n");
for(int i = 0; i < len; i++)
printf("%d ", sa[i]);
printf("\n");
printf("Height:\n");
for(int i = 0; i < len; i++)
printf("%d ", height[i]);
printf("\n");
return 0;
}