Cod sursa(job #3242312)

Utilizator Mihai_999Diaconeasa Mihai Mihai_999 Data 10 septembrie 2024 23:12:30
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <stack>
#include <string>
#define nl '\n'

using namespace std;

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

const int NMAX = 100001, SIGMA = 26, NODES_MAX = 120000;
struct node
{
    int childs[SIGMA];
    unsigned short finished;
    char childsNr;
    int tata;
    char ch;
};

stack<int> st; /// stiva sa reutilizez
node trie[NODES_MAX];
int n = 1, i, op, sz, it, look;
string s;

int get_place()
{
    if (st.empty())
        return ++n;
    else
    {
        op = st.top();
        st.pop();
        return op;
    }
}

void add()
{
    i = 1;
    sz = s.size();
    for (it = 0; it < sz; it++)
    {
        look = s[it]-'a';
        if (!trie[i].childs[look])
        {
            trie[i].childs[look] = get_place();
            trie[i].childsNr++;
        }
        trie[trie[i].childs[look]].tata = i;
        trie[trie[i].childs[look]].ch = s[it];
        i = trie[i].childs[look];
    }
    trie[i].finished++;
    return;
}

void sterge()
{
    i = 1;
    sz = s.size();
    for (it = 0; it < sz; it++)
    {
        look = s[it]-'a';
        i = trie[i].childs[look];
    }
    trie[i].finished--;
    while (i != 1 && !trie[i].childsNr && !trie[i].finished)
    {
        look = trie[i].ch-'a';
        trie[trie[i].tata].childsNr--;
        trie[trie[i].tata].childs[look] = 0;
        st.push(i);
        i = trie[i].tata;
    }
    return;
}

int countApp()
{
    i = 1;
    sz = s.size();
    for (it = 0; it < sz; it++)
    {
        look = s[it]-'a';
        if (!trie[i].childs[look])
            return 0;
        i = trie[i].childs[look];
    }
    return trie[i].finished;
}

int longestPrefix()
{
    i = 1;
    sz = s.size();
    op = 0;
    for (it = 0; it < sz; it++)
    {
        look = s[it]-'a';
        if (!trie[i].childs[look])
            return op;
        i = trie[i].childs[look];
        op++;
    }
    return op;
}

int main()
{
    while (fin >> op)
    {
        fin >> s;
        if (op == 0)
            add();
        else if (op == 1)
            sterge();
        else if (op == 2)
            fout << countApp() << nl;
        else if (op == 3)
            fout << longestPrefix() << nl;
    }
    return 0;
}