Cod sursa(job #2629403)

Utilizator dimi999Dimitriu Andrei dimi999 Data 20 iunie 2020 15:14:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>
using namespace std;

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

struct node
{
    int nrap, nrc;

    node* sons[30];

    node()
    {
        for(int i = 0; i <= 25; i++)
            sons[i] = NULL;

        nrap = nrc = 0;
    }
};

node* inserttrie(node *trie, char *s)
{
    if(trie == NULL)
        trie = new node;

    trie->nrap++;

    if(s[0] == '\0')
        trie->nrc++;
    else
        trie->sons[s[0] - 'a'] = inserttrie(trie->sons[s[0] - 'a'], s + 1);

    return trie;
}

node* deletetrie(node *trie, char *s)
{
    trie->nrap --;

    if(s[0] == '\0')
        trie->nrc--;
    else
        trie->sons[s[0] - 'a'] = deletetrie(trie->sons[s[0] - 'a'], s + 1);

    if(trie->nrap == 0)
        trie = NULL;

    return trie;
}

int getap(node *trie, char *s)
{
    if(trie == NULL)
        return 0;

    if(s[0] == '\0')
        return trie->nrc;

    return getap(trie->sons[s[0] - 'a'], s + 1);
}

int getprefix(node *trie, char *s)
{
    if(trie == NULL)
        return -1;

    if(s[0] == '\0')
        return 0;

    return 1 + getprefix(trie->sons[s[0] - 'a'], s + 1);
}

int main()
{
    int op;
    char s[25];
    node* trie = NULL;

    while(fin >> op)
    {
        fin >> s;

        if(op == 0)
            trie = inserttrie(trie, s);

        if(op == 1)
            trie = deletetrie(trie,s);

        if(op == 2)
            fout << getap(trie, s) << '\n';

        if(op == 3)
            fout << getprefix(trie, s) << '\n';
    }

    return 0;
}