Cod sursa(job #1959817)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 9 aprilie 2017 22:35:38
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");

const int NMax = 2000003;
const int sigma = 27;

struct Trie{
    int words;
    int pref;
    int sons[sigma];
};

Trie T[NMax];
int x,dim = 0;
char w[sigma],cuv[sigma];

void add(char x[]){
    int node = 0;
    for(int i = 0; x[i] != 0; ++i){
        int next = T[node].sons[x[i] - 'a'];
        if(next == 0){
            next = ++dim;
            T[node].sons[x[i] - 'a'] = next;
        }
        T[next].pref ++;
        node = next;
    }
    T[node].words++;
}
void del(char x[]){
    int node = 0;
    for(int i = 0; x[i] != 0; ++i){
        int next = T[node].sons[x[i] - 'a'];
        T[next].pref--;
        node = next;
    }
    T[node].words--;
}
int words(char x[]){
    int node = 0;
    for(int i = 0; x[i] != 0; ++i){
        int next = T[node].sons[x[i] - 'a'];
        if(next == 0)
            return 0;
        node = next;
    }
    return T[node].words;
}
int pref(char x[]){
    int node = 0,len = 0;
    for(int i = 0; x[i] != 0; ++i){
        int next = T[node].sons[x[i] - 'a'];
        if(next == 0)
            break;
        if(T[next].pref > 0)
            len++;
        node = next;
    }
    return len;
}
int main()
{
    while(f >> x){
        f >> cuv;
        if(x == 0) add(cuv);
        if(x == 1) del(cuv);
        if(x == 2) g << words(cuv) << '\n';
        if(x == 3) g << pref(cuv) << '\n';
    }
    return 0;
}