Pagini recente » Cod sursa (job #2186039) | Cod sursa (job #1180500) | Rating Dinu Ema (emadinu) | Arhiva de probleme | Cod sursa (job #1138398)
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define ch (*s - 'a')
using namespace std;
struct trie {
int word;
int prefix;
trie *edge[30];
trie () { word = prefix = 0;
memset(edge , 0 , sizeof(edge));}
};
trie *T = new trie;
void addword(trie *nod, char *s)
{
if (*s == '\n') {nod->word += 1; return;}
if (nod->edge[ch ] == 0 )
{
nod ->edge[ch] = new trie;
nod->prefix++;
}
addword(nod->edge[ch],s+1);
}
int delword(trie *nod, char *s)
{
if (*s == '\n') nod->word -=1;
else
if (delword(nod->edge[ch],s+1))
{
nod->edge[ch] = 0;
nod->prefix--;
}
if (nod->word == 0 && nod->prefix == 0 && nod != T)
{ delete nod; return 1; }
return 0;
}
int nword(trie *nod,char *s)
{
if (*s == '\n') { return nod->word; }
if (nod->edge[ch] )
return nword(nod->edge[ch],s+1);
return 0;
}
int npref(trie *nod,char *s, int k)
{
if ((*s == '\n' )|| (nod->edge[ch] == 0))
return k;
return npref(nod->edge[ch],s+1,k+1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out" , "w", stdout);
char s[ 32 ];
fgets (s, 32 , stdin);
while ( !feof(stdin) )
{
switch ( s[0] )
{
case '0' : addword(T,s+2); break;
case '1' : delword(T,s+2); break;
case '2' : printf("%d\n",nword(T,s+2) ); break;
case '3' : printf("%d\n",npref(T,s+2,0)); break;
}
fgets (s, 32 , stdin);
}
return 0;
}