2019HDU多校第二场 1009.I Love Palindrome String(回文树)

问所有长度的回文子串满足其一半(向上取整)也是回文串的个数。

对原串建出回文树,并且建立fail树,一个节点在fail树上的父亲是其回文后缀,因此从根节点向下dfs,某个长度的一半如果曾经出现过,那么就找到了长度的一半也是回文的回文子串。
统计其出现次数,即可求出答案。

*关于用马拉车确定一个回文串的一半是不是也是回文:看到有人用马拉车+回文树解决这题,马拉车数组存的是以当前位置为回文中心的回文半径。定位到一个串一半位置的中心,看他的半径是否大于等于串长的一半,即可判断串的一半是不是也是回文串。

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int maxn = 3e5 + 5;

int ans[maxn];
char s[maxn];

struct Pam {
    int next[maxn][26];
    int fail[maxn];
    int len[maxn];// 当前节点表示回文串的长度
    int vis[maxn];
    int cnt[maxn];
    int S[maxn];
    vector<int> G[maxn];
    int last, n, p;

    int newNode(int l) {
        memset(next[p], 0, sizeof(next[p]));
        len[p] = l;
        cnt[p] = 0;
        G[p].clear();
        return p++;
    }

    void init() {
        n = last = p = 0;
        newNode(0);
        newNode(-1);
        S[n] = -1;
        fail[0] = 1;
    }

    int getFail(int x) {
        while (S[n - len[x] - 1] != S[n]) {
            x = fail[x];
        }
        return x;
    }

    void add(int c) {
        S[++n] = c;
        int cur = getFail(last);
        if (!next[cur][c]) {
            int now = newNode(len[cur] + 2);
            fail[now] = next[getFail(fail[cur])][c];
            next[cur][c] = now;
            G[fail[now]].push_back(now);
        }
        last = next[cur][c];
        ++cnt[last];
    }

    void update() {
        for (int i = p - 1; i >= 0; i--) {
            cnt[fail[i]] += cnt[i];
        }
    }

    void build() {
        init();
        vis[1] = 1;
        for (int i = 0; s[i]; i++) {
            add(s[i] - 'a');
        }
        update();
    }


    void dfs(int x) {
        if (vis[(int) ceil(1.0 * len[x] / 2)]) {
            ans[len[x]] += cnt[x];
        }
        ++vis[len[x]];
        for (auto v : G[x]) {
            dfs(v);
        }
        --vis[len[x]];
    }
} pam;

int main() {
    while (~scanf("%s", s)) {
        pam.build();
        pam.dfs(0);
        int len = strlen(s);
        for (int i = 1; i <= len; ++i) {
            printf("%d", ans[i]);
            if (i < len) {
                printf(" ");
            }
            ans[i] = pam.vis[i] = 0;
        }
        printf("\n");
    }
    return 0;
}
发布了156 篇原创文章 · 获赞 20 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Cymbals/article/details/97391112