Cod sursa(job #2201065)

Utilizator Horia14Horia Banciu Horia14 Data 3 mai 2018 13:42:31
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include<cstdio>
#include<cstring>
#define MAX_LEN 20
#define SIGMA 26
using namespace std;

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

struct trieNode* root;

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

void insertWord(struct trieNode* root, char* word) {
    struct trieNode* node = root;
    int len = strlen(word);
    for(int i = 0; i < len; 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(struct trieNode* root, char* word) {
    struct trieNode* node = root;
    int len = strlen(word);
    int i = 0;
    while(i < len && node->child[word[i]-'a'] != NULL) {
        node = node->child[word[i]-'a'];
        i++;
    }
    if(i == len)
        return node->fin;
    return 0;
}

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

void deleteWord(struct trieNode* root, char* word) {
    struct trieNode* node = root;
    struct trieNode* node2 = root;
    int len = strlen(word);
    for(int i = 0; i < len; 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+2];
    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 == 0)
            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;
}