Cod sursa(job #2123758)

Utilizator SenibelanMales Sebastian Senibelan Data 6 februarie 2018 16:43:08
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <iostream>
#include <cstring>

using namespace std;

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

struct Trie{
    int number_of_sons, words;
    char letter;
    Trie * Sons[28];

    Trie(){
        number_of_sons = 0;
        words = 0;
        for(int i = 0; i <= 26; ++i)
            Sons[i] = NULL;
    }
};

Trie * Start = new Trie;

void Add(Trie * node, char * word){
    if(strlen(word) == 0)
        node->words++;
    else{
        int index = word[0] - 'a' + 1;
        if(node->Sons[index] == NULL){
            node->Sons[index] = new Trie;
            node->number_of_sons++;
        }
        Add(node->Sons[index], word + 1);
    }
}

bool Delete(Trie * node, char * word){
    if(strlen(word) == 0)
        node->words--;
    else{
        int index = word[0] - 'a' + 1;
        if(!Delete(node->Sons[index], word + 1)){
            node -> number_of_sons--;
            node -> Sons[index] = NULL;
        }
    }
    return node -> number_of_sons;
}

int Count(Trie * node, char * word){
    if(strlen(word) == 0)
        return node->words;
    else{
        int index = word[0] - 'a' + 1;
        if(!(node->Sons[index]))
            return 0;
        return Count(node->Sons[index], word + 1);
    }
}

int Longest_Common_Prefix(Trie * node, char * word, int level){
    if(strlen(word) == 0)
        return level;
    else{
        int index = word[0] - 'a' + 1;
        if(!(node->Sons[index]))
            return level;
        return Longest_Common_Prefix(node -> Sons[index], word + 1, level + 1);
    }
}


int main(){
    int operation;
    char word[25];
    while(in >> operation >> word){
        int index = word[0] - 'a' + 1;
        if(operation == 0)
            Add(Start, word);
        else if(operation == 1){
            Delete(Start, word);
        }
        /*
        else if(operation == 2)
            out << Count(Start, word) << "\n";
        else if(operation == 3)
            out << Longest_Common_Prefix(Start, word, 0) << "\n";
        */
    }
    return 0;
}