【回文自动机】 URAL 2040 Palindromes and Super Abilities 2

通道

题意:每加入一个字符,求增加了多少个本质不同的子串

思路:可知增量要么1要么0,避免超时,字符输出即可。

代码:

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

using namespace std;

typedef long long ll;

const int MAX_N = 5000005;
const int SIG = 2;
struct PTree {
    int nxt[MAX_N][SIG], fail[MAX_N], len[MAX_N];
    char S[MAX_N];
    int last, n, p;
    int newNode (int l) {
        memset(nxt[p], 0, sizeof nxt[p]);
        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(char c) {
        c -= 'a';
        S[++n] = c;
        int cur = getFail(last);
        int pre = p;
        if (!nxt[cur][c]) {
            int now = newNode(len[cur] + 2);
            fail[now] = nxt[getFail(fail[cur])][c];
            nxt[cur][c] = now;
        }
        last = nxt[cur][c];
        return p - pre;
    }    
};

PTree T;
char s[MAX_N];

int main() {
    while (1 == scanf("%s", s)) {
        T.init();
        for (int i = 0; s[i]; ++i) {
            s[i] = T.add(s[i]) + '0';
        }
        puts(s);
    } 
    return 0;
}
View Code

 

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