hdu 4622 Reincarnation(SAM)

题目链接:hdu 4622 Reincarnation

解题思路

对字符串的每个后缀串构建一次后缀自动机,后缀自动机中维护一个tot记录当前串有多少个不同子串,处理出二维ans数组。

代码

#include 
#include 
#include 

using namespace std;
typedef long long ll;
const int maxn = 4005;
const int SIGMA_SIZE = 26;

struct SAM {
    int sz, last;
    int g[maxn<<1][SIGMA_SIZE], pre[maxn<<1], step[maxn<<1];
    int tot;

    void newNode(int s) {
        step[++sz] = s;
        pre[sz] = 0;
        memset(g[sz], 0, sizeof(g[sz]));
    }

    int idx(char ch) { return ch -'a'; }

    void init() {
        tot = 0;
        sz = 0, last = 1;
        newNode(0);
    }

    int insert(char ch) {
        newNode(step[last] + 1);
        int v = idx(ch), p = last, np = sz;

        while (p && !g[p][v]) {
            g[p][v] = np;
            p = pre[p];
        }

        if (p) {
            int q = g[p][v];
            if (step[q] == step[p] + 1)
                pre[np] = q;
            else {
                newNode(step[p] + 1);
                int nq = sz;
                for (int j = 0; j < SIGMA_SIZE; j++) g[nq][j] = g[q][j];

                pre[nq] = pre[q];
                pre[np] = pre[q] = nq;

                while (p && g[p][v] == q) {
                    g[p][v] = nq;
                    p = pre[p];
                }
            }
        } else
            pre[np] = 1;
        tot += step[np] - step[pre[np]];
        last = np;
        return tot;
    }
}SA;

char str[maxn];
int ans[maxn][maxn];

int main () {
    int cas;
    scanf("%d", &cas);
    while (cas--) {
        scanf("%s", str);
        int n = strlen(str), u, v;
        for (int i = 0; i < n; i++) {
            SA.init();
            for (int j = i; j < n; j++)
                ans[i+1][j+1] = SA.insert(str[j]);
        }

        scanf("%d", &n);
        while (n--) {
            scanf("%d%d", &u, &v);
            printf("%d\n", ans[u][v]);
        }
    }
    return 0;
}

你可能感兴趣的:(HDU,GRADE:C,数据结构-后缀自动机)