Cod sursa(job #229343)

Utilizator bogdan2412Bogdan-Cristian Tataroiu bogdan2412 Data 9 decembrie 2008 22:13:59
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int type; string word;

vector<int> trie, trieSum;
vector<vector<pair<int, int> > > muc;

inline int getMuc(int root, char c)
{
    for (size_t k = 0; k < muc[root].size(); k++)
        if (muc[root][k].first == c)
            return muc[root][k].second;
    return -1;
}

inline void add(const string &word, int val)
{
    string :: const_iterator it;
    int root = 0;
    for (it = word.begin(); it != word.end(); it++)
    {
        int next = getMuc(root, *it);
        if (next == -1)
        {
            next = trie.size();
            trie.push_back(0);
            trieSum.resize(trie.size());
            muc.resize(trie.size());
            muc[root].push_back(make_pair(*it, next));
        }

        trieSum[root] += val;
        root = next;
    }
    
    trie[root] += val;
}

inline int query(const string &word)
{
    string :: const_iterator it;
    int root = 0;
    for (it = word.begin(); it != word.end(); it++)
    {
        root = getMuc(root, *it);
        if (root == -1)
            return 0;
    }

    return trie[root];
}

inline int lcp(const string &word)
{
    int lastGoodLen = 0, curLen = 0, root = 0;
    string :: const_iterator it;
    for (it = word.begin(); it != word.end(); it++)
    {
        root = getMuc(root, *it);
        if (root == -1)
            return lastGoodLen;
        curLen++;
        if (trieSum[root] || trie[root])
            lastGoodLen = curLen;
    }

    return lastGoodLen;
}

int main()
{
    freopen("trie.in", "rt", stdin);
    freopen("trie.out", "wt", stdout);

    trie.reserve(500000); trie.resize(1);
    trieSum.reserve(500000); trieSum.resize(1);
    muc.reserve(500000); muc.resize(1);
    for (; cin >> type >> word; )
    {
        if (type == 0)
            add(word, 1);
        if (type == 1)
            add(word, -1);
        if (type == 2)
            printf("%d\n", query(word));
        if (type == 3)
            printf("%d\n", lcp(word));
    }

    return 0;
}