Cod sursa(job #2063532)

Utilizator crion1999Anitei cristi crion1999 Data 11 noiembrie 2017 12:00:27
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
#define NMAX 2000
using namespace std;

ifstream fi("trie.in"); void Input();
ofstream fo("trie.out"); void Output();
struct Trie
{
    int wordCount = 0;
    int prefixCount = 0;
    Trie *sons[26] = {0};
};

void Add(char *word, Trie *trie)
{
    if(*word == 0)
    {
        trie->wordCount++;
        return;
    }
    else
    {
        if(trie->sons[*word - 'a'] == 0)
        {
            trie->sons[*word - 'a'] = new Trie;
            trie->prefixCount++;
        }
    }
    Add(word+1, trie->sons[*word - 'a']);
}
void Remove(char *word, Trie *trie)
{
    if(*word == 0)
    {
        trie->wordCount--;
    }
    else
    {
        Remove(word+1, trie->sons[*word - 'a']);
        if(trie->sons[*word-'a']->wordCount == 0 && trie->sons[*word-'a']->prefixCount == 0)
        {
            delete trie->sons[*word - 'a'];
            trie->sons[*word - 'a'] = 0;
            trie->prefixCount--;
        }
    }
}
int GetFreq(char *word, Trie *trie)
{
    if(*word == 0) return trie->wordCount;
    if(trie->sons[*word - 'a'] == 0) return 0;
    return GetFreq(word+1, trie->sons[*word - 'a']);
}
int GetPrefix(char *word, Trie *trie)
{
    if(*word == 0) return 0;
    if(trie->sons[*word - 'a'] == 0) return 0;
    return 1 + GetPrefix(word+1, trie->sons[*word - 'a']);
}

int main()
{
    Trie *t = new Trie;
    char word[20];
    int c;
    while(fi>>c)
    {
        fi>>word;
        switch(c)
        {
            case 0: Add(word, t); break;
            case 1: Remove(word, t); break;
            case 2: fo<<GetFreq(word, t)<<'\n'; break;
            case 3: fo<<GetPrefix(word, t)<<'\n'; break;
        }
    }
}