Cod sursa(job #2341985)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 12 februarie 2019 15:07:22
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;
struct Trie
{
    int pre;
    int words;
    int sons[30];
}trie[200005];
string word;
int k;
void insert_word(string word)
{
    int node = 0;
    for(int i = 0;i < word.size();i ++)
    {
        int next = trie[node].sons[word[i] - 'a'];
        if(next == 0)trie[node].sons[word[i] - 'a'] = ++k;
        node = trie[node].sons[word[i] - 'a'];
        trie[node].pre++;
    }
    trie[node].words++;
}
void delete_word(string word)
{
    int node = 0;
    for(int i = 0; i < word.size(); i ++)
    {
        int next = trie[node].sons[word[i] - 'a'];
        node = next;
        trie[node].pre--;
    }
    trie[node].words--;
}
int word_query(string word)
{
    int node = 0;
    for(int i = 0; i < word.size(); i ++)
    {
        int next = trie[node].sons[word[i] - 'a'];
        if(next == 0)return 0;
        node = next;
    }
    return trie[node].words;
}
int prefix_query(string word)
{
    int node = 0;
    for(int i = 0; i < word.size();i ++)
    {
        int next = trie[node].sons[word[i] - 'a'];
        node = next;
        if(trie[node].pre <= 0)return i;
    }
    return word.size();
}
int c;
int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    while(f >> c)
    {
        f >> word;
        if(c == 0)insert_word(word);
        if(c == 1)delete_word(word);
        if(c == 2)g << word_query(word) << "\n";
        if(c == 3)g << prefix_query(word) << "\n";
    }
    return 0;
}