Cod sursa(job #2561636)

Utilizator dragos231456Neghina Dragos dragos231456 Data 29 februarie 2020 00:38:00
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <iostream>
#include <fstream>

using namespace std;

const int SIGMA = 26;

ifstream f("trie.in");
ofstream g("trie.out");

int cmd;
string s;
bool del;

struct node{
    int uses=0;
    int words=0;
    struct node* nodes[SIGMA];
    node() {for(int i=0;i<SIGMA;++i) nodes[i] = NULL;}
};

void add_word(struct node *node,int ind)
{
    int letter;

    ///increase the uses of the letter
    node->uses++;

    ///stop condition
    if(ind == s.size()) {node->words++;return;}

    ///get next node,create if needed
    letter = s[ind]-'a';
    if(node->nodes[letter] == NULL)
    {
        struct node *new_node = new struct node;
        node->nodes[letter] = new_node;
    }

    ///next letter
    add_word(node->nodes[letter],ind+1);
}

void remove_word(struct node *node,int ind)
{
    int letter=-1;
    if(ind < s.size())
    {
        letter = s[ind]-'a';
        remove_word(node->nodes[letter],ind+1);
    }
    else node->words--;

    if(del==1) node->nodes[letter] = NULL;
    node->uses--;
    if(node->uses == 0) free(node), del=1;
    else del=0;
}

int word_frequency(struct node *node,int ind)
{
    int letter;

    ///stop condition
    if(ind == s.size()) return node->words;

    ///next letter
    letter = s[ind]-'a';
    if(node->nodes[letter] == NULL) return 0;
    return word_frequency(node->nodes[letter],ind+1);

}

int common_prefix(struct node *node,int ind)
{
    int letter;
    ///stop condition
    if(ind == s.size()) return ind;

    ///next letter
    letter = s[ind]-'a';
    if(node->nodes[letter] == NULL) return ind;
    return common_prefix(node->nodes[letter],ind+1);
}

void print_trie(struct node* node,int ind)
{
    char letter;
    if(ind==-1) cout<<"ROOT ";
    else
    {
        letter = 'a'+ind;
        cout<<letter<<' '<<node->uses<<' '<<node->words;
    }
    cout<<'\n';

    for(int i=0;i<SIGMA;++i) if(node->nodes[i] != NULL) print_trie(node->nodes[i],i);
}

int main()
{
    struct node *root = new struct node;
    while(f>>cmd)
    {
        f>>s; del=0;
        if(cmd == 0) add_word(root,0);
        if(cmd == 1) del=0, remove_word(root,0);
        if(cmd == 2) g<<word_frequency(root,0)<<'\n';
        if(cmd == 3) g<<common_prefix(root,0)<<'\n';
        //print_trie(root,-1); cout<<'\n';
    }
    return 0;
}