Cod sursa(job #3363317)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 16 august 2026 13:56:27
Problema PScPld Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.57 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("pscpld.in");
ofstream fout ("pscpld.out");

const int LG = 26;

struct trie
{
    trie* children[LG];
    trie* link;
    int lg, cnt;

    trie ()
    {
        link = NULL;
        lg = 0;
        cnt = 0;
        for (int i = 0; i < LG; i++)
            children[i] = NULL;
    }
};

trie *root0, *root1, *last;

vector <trie*> ord;

string s;

void init ()
{
    root0 = new trie ();
    root1 = new trie ();
    root0->lg = -1;
    root0->link = root0;
    root1->lg = 0;
    root1->link = root0;
    last = root1;
}

void extend (int i)
{
    int key = s[i] - 'a';
    trie* node = last;
    while (s[i] != s[i - node->lg - 1])
        node = node->link;
    if (node->children[key] != NULL)
    {
        node = node->children[key];
        node->cnt++;
        last = node;
        return;
    }

    trie* nw = new trie ();
    nw->lg = node->lg + 2;
    if (nw->lg == 1)
        nw->link = root1;
    else
    {
        trie* suf = node->link;
        while (s[i] != s[i - suf->lg - 1])
            suf = suf->link;
        nw->link = suf->children[key];
    }

    node->children[key] = nw;
    nw->cnt = 1;
    last = nw;
    ord.push_back (nw);
}

int main ()
{
    fin >> s;

    init ();
    for (int i = 0; i < s.size (); i++)
        extend (i);
    int rez = 0;
    for (int i = ord.size () - 1; i >= 0; i--)
    {
        ord[i]->link->cnt += ord[i]->cnt;
        rez += ord[i]->cnt;
    }
    fout << rez << '\n';
    return 0;
}