Cod sursa(job #1514214)

Utilizator lflorin29Florin Laiu lflorin29 Data 30 octombrie 2015 20:41:04
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

class Trie {
    private:
    int freq, below;

    Trie* sons[26];

    public:

    Trie()
    {
        freq = below = 0;
        memset(sons, 0, sizeof(sons));
    }

    void add(const string &S, int value)
    {
        Trie *T = this;
        for (auto it : S)
        {
            auto edge = it - 'a';
            if (T->sons[edge] == 0)
                T->sons[edge] = new Trie;
            T = T->sons[edge], T->below += value;
        }
        T->freq += value;
    }

    int lcp(const string &S)
    {
        Trie *T = this;
        int res = 0;
        for (auto it : S)
        {
            auto edge = it - 'a';
            if (T->sons[edge] == 0 or T->sons[edge]->below == 0)
                return res;
            T = T->sons[edge];
            res++;
        }
        return static_cast<int>(S.size());
    }

    int ff(const string &S)
    {
        Trie *T = this;
        for (auto it : S)
        {
            auto edge = it - 'a';
            if (T->sons[edge] == 0)
                return 0;
            T = T->sons[edge];
        }
        return T->freq;
    }
};

int main() {
    ifstream cin("trie.in");
    ofstream cout("trie.out");

    int todo;
    string S;
    Trie *T = new Trie;

    while (cin >> todo >> S) {
        if (todo == 0)
             T->add(S, 1);
          else
              if (todo == 1)
                 T->add(S, -1);
          else
              if (todo == 2)
                 cout << T->ff(S) << '\n';
          else
              cout << T->lcp(S) << '\n';
    }
    return 0;
}