【回文自动机】 HDU 5157 Harry and magic string

通道

题意:求不相交回文对数

思路:dp[i]代表以i为结尾有多少个回文,然后在求个前缀和,dp[i]就代表[1,i]以每一个结尾共有多少个,然后结果就是sum(dp[i-1]*add(s[len-i-1]))

代码:

#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], cnt[MAX_N], num[MAX_N], len[MAX_N], S[MAX_N];
    int last, n, p;
    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;
    }
    int 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];
        return num[last];
    }    
    void count() {
        for (int i = p - 1; i >= 0; --i) cnt[fail[i]] += cnt[i];
    }
};

PTree A, B;
char s[MAX_N];
ll dp[MAX_N];

int main() {
    while (1 == scanf("%s", s)) {
        A.init(), B.init();
        dp[0] = A.add(s[0]);
        for (int i = 1; s[i]; ++i) dp[i] = dp[i - 1] + A.add(s[i]);
        int len = strlen(s);
        A.init();
        ll ans = 0;
        for (int i = len - 1; i >= 0; --i) ans += dp[i - 1] * A.add(s[i]);
        printf("%I64d\n", ans);
    } 
    return 0;
}
View Code

 

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