【BZOJ4480】【JSOI2013】快乐的jyy(回文树)

Description


Solution

建出一个串的PAM,另一个串在上面跑,对于每个节点将第一个串的出现次数与第二个串的次数相乘即可。


Code

/************************************************ * Au: Hany01 * Date: Jun 22nd, 2018 * Prob: [BZOJ4480][JSOI2013] 快乐的jyy * Email: hany01@foxmail.com * Institute: Yali High School ************************************************/

#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;
#define File(a) freopen(a".in", "r", stdin), freopen(a".out", "w", stdout)
#define rep(i, j) for (register int i = 0, i##_end_ = (j); i < i##_end_; ++ i)
#define For(i, j, k) for (register int i = (j), i##_end_ = (k); i <= i##_end_; ++ i)
#define Fordown(i, j, k) for (register int i = (j), i##_end_ = (k); i >= i##_end_; -- i)
#define Set(a, b) memset(a, b, sizeof(a))
#define Cpy(a, b) memcpy(a, b, sizeof(a))
#define x first
#define y second
#define pb(a) push_back(a)
#define mp(a, b) make_pair(a, b)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) ((int)(a).size())
#define INF (0x3f3f3f3f)
#define INF1 (2139062143)
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define y1 wozenmezhemecaia

template <typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, 1 : 0; }
template <typename T> inline bool chkmin(T &a, T b) { return b < a ? a = b, 1 : 0; }

inline int read()
{
    register int _, __; register char c_;
    for (_ = 0, __ = 1, c_ = getchar(); c_ < '0' || c_ > '9'; c_ = getchar()) if (c_ == '-') __ = -1;
    for ( ; c_ >= '0' && c_ <= '9'; c_ = getchar()) _ = (_ << 1) + (_ << 3) + (c_ ^ 48);
    return _ * __;
}

const int maxn = 50005;

int main()
{
#ifdef hany01
    File("bzoj4480");
#endif

    static char s[maxn];
    static int n, las, tot, fa[maxn], ch[maxn][26], len[maxn], sz[maxn], cnt[maxn];
    static LL Ans;

    scanf("%s", s + 1), n = strlen(s + 1);
    len[tot = 1] = -1, fa[0] = fa[1] = 1;
    For(i, 1, n) {
        register int p = las, c = s[i] - 65;
        while (s[i] != s[i - len[p] - 1]) p = fa[p];
        if (!ch[p][c]) {
            register int np = ++ tot, k = fa[p];
            while (s[i] != s[i - len[k] - 1]) k = fa[k];
            len[np] = len[p] + 2, fa[np] = ch[k][c], ch[p][c] = np;
        }
        ++ sz[las = ch[p][c]];
    }
    scanf("%s", s + 1), n = strlen(s + 1);
    for (register int u = 1, i = 1; i <= n; ++ i) {
        int c = s[i] - 65;
        while (u != 1 && (!ch[u][c] || s[i] != s[i - len[u] - 1])) u = fa[u];
        if (ch[u][c] && s[i] == s[i - len[u] - 1]) ++ cnt[u = ch[u][c]];
    }
    Fordown(i, tot, 2) Ans += (LL)cnt[i] * sz[i], cnt[fa[i]] += cnt[i], sz[fa[i]] += sz[i];
    printf("%lld\n", Ans);

    return 0;
}
//燕草如碧丝,秦桑低绿枝。
// -- 李白《春思》
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院