Cod sursa(job #1797006)

Utilizator Impaler_009Mihai Nitu Impaler_009 Data 3 noiembrie 2016 22:28:13
Problema PScPld Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.64 kb
#include <iostream>

using namespace std;

struct node {
    int len, count;
    node *suf, *to[26];
    node(int len, node *suf=NULL) : len(len), suf(suf) {
        count = 0;
        for (int i = 0; i < 26; ++i)
            to[i] = NULL;
    }
};

class PalTree {
 public:
    node *uneven_root, *even_root, *current_suf;
    string s;
    int last;

    bool finished() {
        return last >= s.length();
    }

    void read() {
        cin >> s;
        last = 0;
    }

    PalTree() {
        uneven_root = new node(-1);
        even_root = new node(0, uneven_root);
        current_suf = even_root;
    }

    node* follow_suf(node* d) {
        while(last - d->len - 1 < 0 || s[last] != s[last - d->len - 1])
            d = d->suf;
        return d;
    }

    int advance() {
        node* match_suf = follow_suf(current_suf);
        node* new_suf;
        if (match_suf->to[s[last]-'a'] == NULL) {
            new_suf = new node(match_suf->len + 2);
            match_suf->to[s[last]-'a'] = new_suf;
            if (match_suf == uneven_root) {
                new_suf->suf = even_root;
            } else {
                new_suf->suf = follow_suf(match_suf->suf)->to[s[last]-'a'];
            }
        } else {
            new_suf = match_suf->to[s[last]-'a'];
        }
        current_suf = new_suf;
        current_suf->count = current_suf->suf->count + 1;
        ++last;
        return current_suf->count;
    }
};

int main() {
    PalTree pal_tree;
    pal_tree.read();
    long long ans = 0;
    while(!pal_tree.finished()) {
        ans += pal_tree.advance();
    }
    cout << ans;
}