Cod sursa(job #1427024)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 1 mai 2015 12:57:33
Problema PScPld Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_LEN = 200000;
const int SIGMA = 26;

int str[MAX_LEN];
int length[MAX_LEN];
int link[MAX_LEN];
int value[MAX_LEN];

int to[MAX_LEN][SIGMA];

int lastNode;
int countNodes;
int lengthString;

void initTree()
{
    lengthString = 0;
    countNodes = 2;
    lastNode = 0;

    link[0] = 1;
    length[1] = -1;

    str[ lengthString++ ] = -1;
}

int getLink(int v)
{
    while (str[lengthString - length[v] - 2] != str[lengthString - 1])
        v = link[v];

    return v;
}

void addLetter(int c)
{
    str[ lengthString++ ] = c;
    lastNode = getLink(lastNode);

    if (!to[lastNode][c])
    {
        length[countNodes] = length[lastNode] + 2;
        link[countNodes] = to[getLink(link[lastNode])][c];
        to[lastNode][c] = countNodes++;

        value[countNodes - 1] = value[ link[countNodes - 1] ] + 1;
    }

    lastNode = to[lastNode][c];
}

int main()
{
    ifstream in("pscpld.in");
    ofstream out("pscpld.out");

    initTree();

    char c;
    long long sol = 0;
    while (in >> c)
    {
        addLetter(c);
        sol += value[lastNode];
    }

    out << sol << "\n";

    return 0;
}