Cod sursa(job #1579637)

Utilizator hasmasandragosHasmasan Dragos hasmasandragos Data 24 ianuarie 2016 21:59:21
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 kb
#include <fstream>
#include <string.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");

struct trie
{
    int nrs,cnt;
    trie *son [26];
    trie ()
    {
        cnt=nrs=0;
        memset(son,0,sizeof(son));
    }
};

char s[35]; /// stringul pe care o sa lucram
trie *root = new trie(); /// cream radacina trie-ului , care va avea valoarea initiala asociata egala cu 0

void insert_word (trie *node ,char *s)
{
    if (*s==NULL)
    {
        node->cnt ++;
        return ;
    }
    int delta = *s - 'a';
    if (node->son[delta]==NULL)
    {
        node->son[delta]= new trie();
        node->nrs ++;
    }
    insert_word (node->son[delta],s+1);
}

int word_frequency (trie *node , char *s)
{
    if (*s==NULL)
        return node->cnt;
    int delta = *s - 'a';
    if (node->son[delta]==NULL)
        return 0;
    word_frequency(node->son[delta],s+1);
}

int longest_common_prefix (trie *node , char *s)
{
    if (*s==NULL)
      return 0;
    int delta = *s - 'a';
    if (node->son[delta]==NULL)
     return 0;
    return 1+longest_common_prefix(node->son[delta],s+1);
}

bool erase_word (trie *node , char *s)
{
    if (*s==NULL)
    {
        node->cnt--;
        if (node->cnt==0 && node->nrs==0 && node!=root)
        {
            delete node;
            return 1;
        }
        return 0;
    }
    int delta = *s - 'a';
    if (erase_word(node->son[delta],s+1))
    {
        node->nrs--;
        node->son[delta] = 0;
        if (node->cnt==0 && node->nrs==0 && node!=root)
        {
            delete node;
            return 1;
        }
    }
    return 0;
}

int main()
{
    int op;
    /*
    0 w - adauga o aparitie a cuvantului w in lista
    1 w - sterge o aparitie a cuvantului w din lista
    2 w - tipareste numarul de aparitii ale cuvantului w in lista
    3 w - tipareste lungimea celui mai lung prefix comun al lui w cu oricare cuvant din lista
    */
    while (f>>op>>s)
    {
        if (op==0)
            insert_word(root,s);
        if (op==1)
            erase_word(root,s);
        if (op==2)
            g<<word_frequency(root,s)<<'\n';
        if (op==3)
            g<<longest_common_prefix(root,s)<<'\n';

    }
    return 0;
}