Cod sursa(job #2211984)

Utilizator Horia14Horia Banciu Horia14 Data 12 iunie 2018 18:01:45
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include<cstdio>
#include<cstring>
#define MAX_LEN 20
#define SIGMA 26
using namespace std;

struct trieNode {
    int fin, cnt;
    trieNode* child[SIGMA];
};

trieNode* root;

trieNode* getNode() {
    trieNode* node = new trieNode;
    node->fin = node->cnt = 0;
    for(int i = 0; i < SIGMA; i++)
        node->child[i] = NULL;
    return node;
}

void insertWord(trieNode* root, char* word) {
    trieNode* node = root;
    int length = strlen(word);
    for(int i = 0; i < length; i++) {
        if(node->child[word[i]-'a'] == NULL)
            node->child[word[i]-'a'] = getNode();
        node = node->child[word[i]-'a'];
        ++node->cnt;
    }
    ++node->fin;
}

int searchWord(trieNode* root, char* word) {
    trieNode* node = root;
    int length = strlen(word);
    int i = 0;
    while(i < length && node->child[word[i]-'a'] != NULL) {
        node = node->child[word[i]-'a'];
        i++;
    }
    if(i == length)
        return node->fin;
    else return 0;
}

int prefixSearch(trieNode* root, char* word) {
    trieNode* node = root;
    int length = strlen(word);
    int i = 0;
    while(i < length && node->child[word[i]-'a'] != NULL) {
        node = node->child[word[i]-'a'];
        i++;
    }
    return i;
}

void deleteWord(trieNode* root, char* word) {
    trieNode* node = root;
    trieNode* node2 = root;
    int length = strlen(word);
    for(int i = 0; i < length; i++) {
        node2 = node->child[word[i]-'a'];
        --node2->cnt;
        if(node2->cnt == 0)
            node->child[word[i]-'a'] = NULL;
        if(node->cnt == 0)
            delete node;
        node = node2;
    }
    --node2->fin;
}

int main() {
    int op;
    char word[MAX_LEN+1];
    FILE* fin, *fout;
    fin = fopen("trie.in","r");
    fout = fopen("trie.out","w");
    root = getNode();
    root->cnt = 1;
    while(!feof(fin)) {
        fscanf(fin,"%d%s\n",&op,word);
        if(!op)
            insertWord(root,word);
        else if(op == 1)
            deleteWord(root,word);
        else if(op == 2)
            fprintf(fout,"%d\n",searchWord(root,word));
        else fprintf(fout,"%d\n",prefixSearch(root,word));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}