Pagini recente » Cod sursa (job #3293061) | Clasamentul arhivei ACM | Cod sursa (job #3279325) | Cod sursa (job #3294369) | Cod sursa (job #3289805)
#include <fstream>
#include <string>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct trie{
int aps;
signed char children;
trie* urm[26];
}*root;
void add(trie* nod, char* it)
{
char c=*it;
if(c=='\0')
{
nod->aps++;
return;
}
if(nod->urm[c-'a']==NULL)
{
nod->urm[c-'a']=new trie;
nod->children++;
}
add(nod->urm[c-'a'],++it);
}
bool erase(trie* nod, char* it)
{
char c=*it;
if(c=='\0')
{
nod->aps--;
if(!nod->aps&&!nod->children)
{
delete nod;
return true;
}
return false;
}
bool deleted=erase(nod->urm[c-'a'],++it);
if(deleted)
{
nod->children--;
nod->urm[c-'a']=NULL;
}
if(!nod->aps&&!nod->children)
{
delete nod;
return true;
}
return false;
}
int count_aparitions(trie* nod, char* it)
{
char c=*it;
if(c=='\0')
return nod->aps;
if(nod->urm[c-'a']==NULL)
return 0;
return count_aparitions(nod->urm[c-'a'],++it);
}
int prefix_length(trie* nod, char* it)
{
char c=*it;
if(c=='\0'||nod->urm[c-'a']==NULL)
return 0;
return 1+prefix_length(nod->urm[c-'a'],++it);
}
int main()
{
root=new trie;
int c;
string str;
while(f>>c>>str)
switch(c)
{
case 0:
add(root,&str[0]);
break;
case 1:
erase(root,&str[0]);
break;
case 2:
g<<count_aparitions(root,&str[0])<<'\n';
break;
case 3:
g<<prefix_length(root,&str[0])<<'\n';
break;
}
return 0;
}