Pagini recente » Cod sursa (job #229873) | Cod sursa (job #668945) | Cod sursa (job #2644899) | Cod sursa (job #3260459) | Cod sursa (job #229346)
Cod sursa(job #229346)
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
int type; string word;
vector<int> trie, trieSum;
vector<map<char, 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;
*/
if (muc[root].find(c) != muc[root].end())
return muc[root][c];
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].insert(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;
}