Cod sursa(job #2806566)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 22 noiembrie 2021 19:42:15
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.63 kb
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

#define ALPHABET_SIZE 26
#define MAX_LEN 22

using namespace std;

char line[MAX_LEN + 1];

struct trieNode {
    trieNode* child[ALPHABET_SIZE];
    int nrWords, nrChildren;
};

trieNode *createNode() {
    int i;
    trieNode* newNode = (trieNode*)malloc( sizeof( trieNode ) );

    for ( i = 0; i < ALPHABET_SIZE; i++ )
        newNode->child[i] = NULL;
    newNode->nrWords = newNode->nrChildren = 0;

    return newNode;
}

void insertTrie( trieNode* root, char *word, int length ) {
    int i;
    trieNode* temp = root;

    for ( i = 0; i < length; i++ ) {
        temp->nrChildren++;
        if ( temp->child[word[i]] == NULL )
            temp->child[word[i]] = createNode();
        temp = temp->child[word[i]];
    }

    temp->nrChildren++;
    temp->nrWords++;
}

void deleteTrie( trieNode* root, char *word, int length ) {
    int i;
    trieNode* temp = root;

    for ( i = 0; i < length; i++ ) {
        temp->nrChildren--;
        if ( temp->child[word[i]] == NULL )
            temp->child[word[i]] = createNode();
        temp = temp->child[word[i]];
    }

    temp->nrChildren--;
    temp->nrWords--;
}

int words( trieNode* root, char *word, int length ) {
    int i;
    trieNode* temp = root;

    i = 0;
    while ( i < length && temp != NULL  ) {
        temp = temp->child[word[i]];
        i++;
    }

    if ( temp == NULL )
        return 0;
    return temp->nrWords;
}

int prefix( trieNode* root, char *word, int length ) {
    int i;
    trieNode* temp = root;

    i = 0;
    while ( i < length && temp != NULL && temp->nrChildren > 0 ) {
        temp = temp->child[word[i]];
        i++;
    }

    if ( temp == NULL || temp->nrChildren == 0 )
        i--;
    return i;
}

int main() {
    FILE *fin, *fout;
    int len;
    trieNode* root = createNode();

    fin = fopen( "trie.in", "r" );
    fout = fopen( "trie.out", "w" );

    fgets( line, MAX_LEN + 1, fin );

    while( !feof( fin ) ) {
        len = 0;
        while ( line[len] != 0 ) {
            line[len] -= 'a';
            len++;
        }
        len -= 3;

        line[0] += 'a';
        if ( line[0] == '0' )
            insertTrie( root, line + 2, len );
        else if ( line[0] == '1' )
            deleteTrie( root, line + 2, len );
        else if ( line[0] == '2' )
            fprintf( fout, "%d\n", words( root, line + 2, len ) );
        else if ( line[0] == '3' )
            fprintf( fout, "%d\n", prefix( root, line + 2, len ) );

        fgets( line, MAX_LEN + 1, fin );
    }

    return 0;
}