后缀数组LCP模板

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 10000 + 10;

char s[maxn];
int sa[maxn], t[maxn], t2[maxn], c[maxn], n;
//s:(0 ~ m-1)
void build_sa(int m)
{
    int *x = t, *y = t2;

    for(int i = 0; i < m; i++) c[i] = 0;
    for(int i = 0; i < n; i++) c[x[i] = s[i]]++;
    for(int i = 1; i < m; i++) c[i] += c[i-1];
    for(int i = n - 1; i >= 0; i--) sa[--c[x[i]]] = i;

    for(int k = 1; k <= n; k <<= 1){
        int p = 0;

        for(int i = n - k; i < n; i++) y[p++] = i;
        for(int i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i] - k;

        for(int i = 0; i < m; i++) c[i] = 0;
        for(int i = 0; i < n; i++) c[x[y[i]]]++;
        for(int i = 0; i < m; i++) c[i] += c[i-1];
        for(int i = n - 1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i];

        swap(x, y);
        p = 1; x[sa[0]] = 0;
        for(int i = 1; i < n; i++){
            x[sa[i]] = y[sa[i-1]] == y[sa[i]] && y[sa[i-1]+k] == y[sa[i]+k] ? p-1 : p++;
        }
        if(p >= n) break;
        m = p;
    }
}

int m; //length of MSC
int cmp_suffix(char* pattern, int p){
    return strncmp(pattern, s + sa[p], m);
}

int Rank[maxn], height[maxn];
void getHeight()
{
    int k = 0;
    for(int i = 0; i < n; i++) Rank[sa[i]] = i;
    for(int i = 0; i < n; i++){
        if(k) k--;
        int j = sa[Rank[i]-1];
        while(s[i+k] == s[j+k]) k++;
        height[Rank[i]] = k;
    }
}

int d[maxn][30];
void RMQ_init(int A[], int lenA)
{
    for(int i = 0; i < n; i++) d[i][0] = A[i];
    for(int j = 1; (1<<j) <= n; j++)
        for(int i = 0; i + (1<<j) - 1 < n; i++)
            d[i][j] = min(d[i][j-1], d[i + (1<<(j-1))][j-1]);
}

int RMQ(int L, int R)
{
    int a = Rank[L]+1, b = Rank[R]+1;
    if(a > b) swap(a,b);b--;
    cout<<"a : "<<a<<" b : "<<b<<endl;
    int  k = log(b-a+1.0)/log(2.0);
    return min(d[a][k],d[b-(1<<k)+1][k]);
}

int main()
{
    //freopen("1.in","r",stdin);
    while(~scanf("%s", s)){
        n = strlen(s);
        s[n] = '$';
        n+=1;
        build_sa(128);
        getHeight();
        for(int i = 0; i < n; i++){
            int pos = sa[i];
            for(int j = pos; j < n; j++){
                printf("%c",s[j]);
            }printf("\n");
        }printf("\n");

        for(int i = 0; i < n; i++) printf("%d ",sa[i]);printf("\n");
        for(int i = 0; i < n; i++) printf("%d ", Rank[i]);printf("\n");
        for(int i = 0; i < n; i++) printf("%d ", height[i]); printf("\n");
        RMQ_init(height, n);
        int cas;scanf("%d",&cas);
        //
        while(cas--){
            int L, R;
            scanf("%d%d",&L, &R);
            int res = RMQ(L, R);
            printf("res : %d\n",res);
        }

    }
    return 0;
}
posted @ 2017-07-20 20:30  />.<\  阅读(230)  评论(0编辑  收藏  举报