Cod sursa(job #1741045)

Utilizator razvandRazvan Dumitru razvand Data 12 august 2016 20:47:51
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream in("trie.in");
ofstream out("trie.out");

int trie[100003][30];
int down[100003];
int fina[100003];
int T = 0;

void ad(string s, int add) {

    int C = 0;

    for(int i = 0; i < s.size(); i++) {
        down[C] += add;
        if(trie[C][s[i]-'a'] == 0)
            trie[C][s[i]-'a'] = ++T;
        C = trie[C][s[i]-'a'];
    }

    down[C] += add;
    fina[C] += add;

}

int ap(string s) {
    int C = 0;
    for(int i = 0; i < s.size(); i++) {
        if(trie[C][s[i]-'a'] == 0)
            return 0;
        C = trie[C][s[i]-'a'];
    }
    return fina[C];
}

int ln(string s) {

    int C = 0;

    for(int i = 0; i < s.size(); i++) {
        if(trie[C][s[i]-'a'] == 0 || down[trie[C][s[i]-'a']] <= 0)
            return i;
        C = trie[C][s[i]-'a'];
    }

    return s.size();

}

int main() {

    int t;
    string S;

    while(in >> t) {

        in >> S;

        if(t == 0)
            ad(S, 1);
        if(t == 1)
            ad(S, -1);
        if(t == 2)
            out << ap(S) << '\n';
        if(t == 3)
            out << ln(S) << '\n';

    }

    return 0;
}