// 字符串处理 后缀数组
void build_sa( char * s ) // 字符串从第一位开始读入,第0位任意填入一个字符便于操作
{
int j, num, n = strlen( s )-1, m = 200, *x = a1, *y = a2;
for( int i = 1; i <= m; i++ ) c[i] = 0;
for( int i = 1; i <= n; i++ ) c[ x[i] = s[i] ]++;
for( int i = 2; i <= m; i++ ) c[i] += c[i-1];
for( int i = 1; i <= n; i++ ) sa[ c[ x[i] ]-- ] = i;
for( int k = 1; k <= n; k <<= 1 )
{
num = 0;
for( int i = n-k+1; i <= n; i++ ) y[++num] = i;
for( int i = 1; i <= n; i++ ) if( sa[i] > k ) y[++num] = sa[i]-k;
for( int i = 1; i <= m; i++ ) c[i] = 0;
for( int i = 1; i <= n; i++ ) c[ x[i] ]++;
for( int i = 2; i <= m; i++ ) c[i] += c[i-1];
for( int i = n; i >= 1; i-- ) sa[ c[ x[ y[i] ] ]-- ] = y[i];
swap( x, y );
num = 1;
x[ sa[1] ] = 1;
for( int i = 2; i <= n; i++ )
x[ sa[i] ] = y[ sa[i] ] == y[ sa[i-1] ] && y[ sa[i]+k ] == y[ sa[i-1]+k ]? num: ++num;
if( num == n ) break;
m = num;
}
num = 0;
for( int i = 1; i <= n; i++ )
{
if( x[i] == 1 ) continue;
if( num ) num--;
j = sa[ x[i]-1 ];
while( s[i+num] == s[j+num] ) num++;
height[ x[i] ] = num;
}
}
【数据结构】后缀数组
最新推荐文章于 2024-07-15 11:27:12 发布