Pagini recente » Cod sursa (job #809061) | Cod sursa (job #846484) | Cod sursa (job #601705) | Cod sursa (job #216233) | Cod sursa (job #2164522)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
/* Smart Pointers don't fit in the memory limit *sad face* :( */
class Node
{
private:
int pass=0;
int ending=0;
vector<Node*>vec;
public:
Node(void):vec(26,NULL)
{}
bool IsNode(char c)
{
if(vec[c-'a']!=NULL)
return true;
else
return false;
}
Node* GetNode(char c)
{
return vec[c-'a'];
}
void MakeNode(char c)
{
vec[c-'a']=new Node;
}
void DelNode(char c)
{
delete vec[c-'a'];
vec[c-'a']=NULL;
}
void IncrementPass(void)
{
pass++;
}
void IncrementEnding(void)
{
ending++;
}
void DecrementPass(void)
{
pass--;
}
void DecrementEnding(void)
{
ending--;
}
int GetPass(void)
{
return pass;
}
int GetEnding(void)
{
return ending;
}
};
class Trie
{
private:
Node* Head;
public:
Trie(void): Head(new Node)
{}
void AddWord(string s)
{
Node* now=Head;
for(unsigned i=0;i<s.length();i++)
{
if(!now->IsNode(s[i]))
{
now->MakeNode(s[i]);
}
now=now->GetNode(s[i]);
now->IncrementPass();
if(i==s.length()-1)
now->IncrementEnding();
}
}
void DelWord(string s)
{
Node* now=Head;
for(unsigned i=0;i<s.length();i++)
{
if(now->GetNode(s[i])->GetPass()==1)
{
now->DelNode(s[i]);
break;
}
now=now->GetNode(s[i]);
now->DecrementPass();
if(i==s.length()-1)
now->DecrementEnding();
}
}
unsigned GetEnding(string s)
{
Node* now=Head;
for(unsigned i=0;i<s.length();i++)
{
now=now->GetNode(s[i]);
if(now==NULL)
return 0;
}
return now->GetEnding();
}
unsigned GetMaxPrefix(string s)
{
Node* now=Head;
unsigned max_len=0;
for(unsigned i=0;i<s.length();i++)
{
now=now->GetNode(s[i]);
if(now==NULL)
return max_len;
max_len++;
}
return max_len;
}
};
int main()
{
Trie t;
int op;
string s;
while(fin>>op>>s)
{
switch(op)
{
case 0:
t.AddWord(s);
break;
case 1:
t.DelWord(s);
break;
case 2:
fout<<t.GetEnding(s)<<'\n';
break;
case 3:
fout<<t.GetMaxPrefix(s)<<'\n';
break;
}
}
return 0;
}