Cod sursa(job #2073336)

Utilizator delia_ioanaCeapa Delia Ioana delia_ioana Data 22 noiembrie 2017 23:01:36
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>

using namespace std;


struct Trie {
    int isEnd, isPassed;
    vector<Trie*> next;

    Trie() {
        isEnd = 0;
        isPassed = 0;
        for (int i = 0; i < 26; i ++)
            next.push_back(NULL);
    }
};

Trie *t = new Trie();

void add(Trie *&tr, string &word, int k) {
    tr->isPassed ++;

    if (k == word.size()) {
        tr->isEnd ++;
        return;
    }

    if (!tr->next[word[k] - 'a']) {
        tr->next[word[k] - 'a'] = new Trie();
    }

    add(tr->next[word[k] - 'a'], word, k + 1);

}

void remove(Trie *&tr, string &word, int k) {
    tr->isPassed --;

    if (k == word.size()) {
        if (tr->isEnd > 0)
            tr->isEnd --;
        return;
    }

    if (!tr->next[word[k] - 'a']) {
        return;
    }

    remove(tr->next[word[k] - 'a'], word, k + 1);
}

int count(Trie *&tr, string &word, int k) {
    if (k == word.size()) {
        return tr->isEnd; 
    }

    if (!tr->next[word[k] - 'a']) {
        return 0;
    }

    return count(tr->next[word[k] - 'a'], word, k + 1);
}

int prefix(Trie *&tr, string &word, int k) {
    if (k == word.size() && tr->isPassed > 0) {
        return word.size(); 
    }

    if (!tr->next[word[k] - 'a'] || tr->next[word[k] - 'a']->isPassed == 0) {
        return k;
    }

    return prefix(tr->next[word[k] - 'a'], word, k + 1);
}

int main() {
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    string command;
    while (getline(cin, command)) {
        string word = command.substr(2);
        if (command[0] == '0') {
            add(t, word, 0);
        }
        if (command[0] == '1') {
            remove(t, word, 0);
        }
        if (command[0] == '2') {
            cout << count(t, word, 0) << endl;
        }
        if (command[0] == '3') {
            cout << prefix(t, word, 0) << endl;
        }
    }

    return 0;
}