Cod sursa(job #2222124)

Utilizator inquisitorAnders inquisitor Data 16 iulie 2018 15:29:11
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.62 kb
#include <fstream>
#include <cstring>
#include <cctype>
#define maxWordLength 20
using namespace std;

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

struct node{
    int occurences;
    struct node *edge[26];

    node(){
        occurences = 0;
        for(int i = 0; i < 26; i++){
            edge[i] = NULL;
        }
    }
};
node *root = new node;

void Insert(char word[]){
    node *current = root;
    int len = strlen(word), index;

    for(int i = 0; i < len; i++, current = current -> edge[index]){
        index = tolower(word[i]) - 'a';

        if(current -> edge[index] == NULL){
            current -> edge[index] = new node;
        }
    }current -> occurences++;
}

void Delete(char word[]){
    int len = strlen(word), index, it = -1, sons;
    node *pathStack[maxWordLength + 1], *current = root;

    pathStack[++it] = current;

    for(int i = 0; i < len; i++, current = current -> edge[index]){
        index = tolower(word[i]) - 'a';
        if(current -> edge[index] == NULL) return;
        pathStack[++it] = current -> edge[index];
    }
    if(current -> occurences > 1){
        current -> occurences--;
        return;
    }current -> occurences--;

    for(int i = it; i > 0; i--){
        sons = 0;

        for(int j = 0; j < 26; j++){
            sons += !!(pathStack[i] -> edge[j]);
        }
        if(sons || pathStack[i] -> occurences) return;
        else{
            delete pathStack[i];
            pathStack[i - 1] -> edge[tolower(word[i - 1]) - 'a'] = NULL;
        }
    }
}

int Search(char word[]){
    node *current = root;
    int len = strlen(word), index;

    for(int i = 0; i < len; i++, current = current -> edge[index]){
        index = tolower(word[i]) - 'a';
        if(current -> edge[index] == NULL) return 0;
    }
    return current -> occurences;
}

int LongestPrefix(char word[]){
    node *current = root;
    int len = strlen(word), index, prefix = 0;

    for(int i = 0; i < len; i++, current = current -> edge[index]){
        index = tolower(word[i]) - 'a';
        if(current -> edge[index] == NULL) break;
        prefix++;
    }
    return prefix;
}

int main()
{
    int task; char word[21];

    while(scanf("%d %s", &task, word))
    {
        switch(task)
        {
            case 0: Insert(word);
                    break;

            case 1: Delete(word);
                    break;

            case 2: printf("%d\n", Search(word));
                    break;

            case 3: printf("%d\n", LongestPrefix(word));
                    break;
        }
    }

    return 0;
}