Cod sursa(job #2613259)

Utilizator CosminMorarMorar Cosmin Andrei CosminMorar Data 9 mai 2020 15:24:19
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <string>
#define LEN 26
#define CH word[index] - 'a'
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int task;
string word;

struct trie {
    int cnt, cnt_fii;
    trie *fiu[LEN];

    trie() {
        cnt = cnt_fii = 0;
        for (int i = 0; i < LEN; i++)
            fiu[i] = nullptr;
    }
};

void ins(trie *nod, string word, int index) {
    if (index == word.length()) {
        nod->cnt++;
        return;
    }
    if (nod->fiu[CH] == nullptr) {
        nod->fiu[CH] = new trie;
        nod->cnt_fii++;
    }
    ins(nod->fiu[CH], word, index + 1);
}

void del(trie *nod, string word, int index) {
    if (index == word.length()) {
        nod->cnt--;
        return;
    }

    del(nod->fiu[CH], word, index + 1);

    if (!nod->fiu[CH]->cnt && !nod->fiu[CH]->cnt_fii) { /// stergem fiul daca e nevoie
        delete nod->fiu[CH];
        nod->fiu[CH] = nullptr;
        nod->cnt_fii--;
    }
}

int occurencies(trie *nod, string word, int index) {
    if (index == word.length())
        return nod->cnt;
    if (nod->fiu[CH] == nullptr)
        return 0;
    return occurencies(nod->fiu[CH], word, index + 1);
}

int longest_pref(trie *nod, string word, int index) {
    if (index == word.length() || nod->fiu[CH] == nullptr)
        return index;
    return longest_pref(nod->fiu[CH], word, index + 1);
}

int main() {
    trie *root = new trie;
    while (fin >> task >> word) {
        if (task == 0)
            ins(root, word, 0);
        else if (task == 1)
            del(root, word, 0);
        else if (task == 2)
            fout << occurencies(root, word, 0) << '\n';
        else
            fout << longest_pref(root, word, 0) << '\n';
    }
    return 0;
}