Cod sursa(job #569035)
#include <cstdio>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#define f first
#define s second
string cuv;
vector <int> trie, triesum;
vector <vector <pair<int, int> > > v;
inline void addTrie(const string &cuv, int val)
{
string::const_iterator it;
int i, next, root=0;
for (it=cuv.begin(); it!=cuv.end(); it++)
{
next=-1;
for (i=0; i<v[root].size(); i++)
if (v[root][i].f==*it)
next=v[root][i].s;
if (next==-1)
{
next=trie.size();
trie.push_back(0);
triesum.resize(trie.size());
v.resize(trie.size());
v[root].push_back (make_pair (*it, next));
}
triesum[root]+=val;
root=next;
}
trie[root]+=val;
triesum[root]+=val;
}
inline int countWords(const string &cuv)
{
string::const_iterator it;
int i, next, root=0;
for (it=cuv.begin(); it!=cuv.end(); it++)
{
next=-1;
for (i=0; i<v[root].size(); i++)
if (v[root][i].f==*it)
next=v[root][i].s;
if (next==-1) return 0;
root=next;
}
return trie[root];
}
inline int longestPrefix(const string &cuv)
{
string::const_iterator it;
int i, next, root=0, l=0;
for (it=cuv.begin(); it!=cuv.end(); it++)
{
next=-1;
for (i=0; i<v[root].size(); i++)
if (v[root][i].f==*it)
next=v[root][i].s;
if (next==-1) return l;
root=next;
if (!triesum[root]) return l;
l++;
}
return l;
}
int main()
{
ifstream fin("trie.in");
freopen("trie.out","w",stdout);
trie.push_back(0);
triesum.push_back(0);
int t;
string::iterator it;
v.resize(1);
while (!fin.eof())
{
fin >> t >> cuv;
if (!t) addTrie(cuv, 1);
if (t==1) addTrie(cuv, -1);
if (t==2) printf("%d\n",countWords(cuv));
if (t==3) printf("%d\n",longestPrefix(cuv));
}
return 0;
}