【回文自动机】 GYM 100548G The Problem to Slow Down You

通道

题意:2个字符串,求相同的回文串对数 (S, T), 其中S == T

思路:由于并不需要本质不同,所以需要count一下,然后相同部分肯定dfs是一样的,累加即可。

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long ll;

const int MAX_N = 600005;
const int SIG = 26 ;

struct PTree {
    int nxt[MAX_N][SIG], fail[MAX_N],  num[MAX_N], len[MAX_N], S[MAX_N];
    int last, n, p;ll cnt[MAX_N];
    int newNode (int l) {
        memset(nxt[p], 0, sizeof nxt[p]);
        cnt[p] = num[p] = 0;
        len[p] = l;
        return p++;
    }
    void init() {
        p = last = n = 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) {
        c -= 'a';
        S[++n] = c;
        int cur = getFail(last);
        if (!nxt[cur][c]) {
            int now = newNode(len[cur] + 2);
            fail[now] = nxt[getFail(fail[cur])][c];
            nxt[cur][c] = now;
            num[now] = num[fail[now]] + 1;
        }
        last = nxt[cur][c];
        ++cnt[last];
    }    
    void count() {
        for (int i = p - 1; i >= 0; --i) cnt[fail[i]] += cnt[i];
    }
};

PTree A, B;

ll dfs(int u, int v) {
    ll ret = 0;
    for (int i = 0; i < 26; ++i) {
        if (A.nxt[u][i] && B.nxt[v][i]) {
            int z1 = A.nxt[u][i], z2 = B.nxt[v][i];
            ret += A.cnt[z1] * B.cnt[z2] + dfs(A.nxt[u][i], B.nxt[v][i]);
        }
    }
    return ret;
}

char s1[MAX_N], s2[MAX_N];

int main() {
    int T, cas = 0;
    scanf("%d", &T);
    while (T-- > 0) {
        scanf("%s%s", s1, s2);
        A.init(); B.init();
        for (int i = 0; s1[i]; ++i) A.add(s1[i]);
        A.count();
        for (int i = 0; s2[i]; ++i) B.add(s2[i]);
        B.count();
        ll ans = dfs(0, 0) + dfs(1, 1);
        printf("Case #%d: %I64d\n", ++cas, ans);
    }
    return 0;
}
View Code

 

posted @ 2015-08-15 21:28  mithrilhan  阅读(226)  评论(0编辑  收藏  举报