Cod sursa(job #2034972)

Utilizator Horia14Horia Banciu Horia14 Data 8 octombrie 2017 18:42:12
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.38 kb
#include<cstdio>
#include<cstring>
#define SIGMA 26
#define MAX_LEN 20
using namespace std;

struct trieNode {
    int cnt, fin;
    struct 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* key) {
    struct trieNode* node = root;
    int length = strlen(key);
    for(int i=0; i<length; i++) {
        if(node->child[key[i]-'a'] == NULL)
            node->child[key[i]-'a'] = getNode();
        node = node->child[key[i]-'a'];
        ++node->cnt;
    }
    ++node->fin;
}

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

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

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

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