Cod sursa(job #1986985)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 29 mai 2017 16:23:03
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

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

const int NMax = 20000003;
const int sigma = 27;

struct node{
    int pre;
    int words;
    int sons[sigma];
};

int S;
node T[NMax];


void insert_word(string str){
    int node = 0;
    for(int i = 0; i < str.size(); ++i){
        int next = T[node].sons[str[i] - 'a'];
        if(next == 0){
            T[node].sons[str[i] - 'a'] = ++S;
        }
        node = T[node].sons[str[i] - 'a'];
        T[node].pre++;
    }
    T[node].words++;
}
void delete_word(string str){
    int node = 0;
    for(int i = 0; i < str.size(); ++i){
        int next = T[node].sons[str[i] - 'a'];
        node = next;
        T[node].pre--;
    }
    T[node].words--;
}
int words_query(string str){
    int node = 0;
    for(int i = 0; i < str.size(); ++i){
        int next = T[node].sons[str[i] - 'a'];
        if(next == 0)
            return 0;
        node = next;
    }
    return T[node].words;
}
int pre_query(string str){
    int node = 0;
    for(int i = 0; i < str.size(); ++i){
        int next = T[node].sons[str[i] - 'a'];

        node = next;
        if(T[node].pre <= 0)
            return i;
    }
    return str.size();
}
int main()
{
    int x;
    while(f >> x){
        string cuv;
        f >> cuv;
        if(x == 0) insert_word(cuv);
        if(x == 1) delete_word(cuv);
        if(x == 2) g << words_query(cuv) << '\n';
        if(x == 3) g << pre_query(cuv) << '\n';
    }
    return 0;
}