Pagini recente » Cod sursa (job #920955) | Cod sursa (job #2133905) | Cod sursa (job #485109) | Cod sursa (job #1671781) | Cod sursa (job #2305241)
#include<cstdio>
#include<cstring>
using namespace std;
FILE*si=fopen("trie.in","r");
FILE*so=fopen("trie.out","w");
struct Trie{
int ct,ct_son;
Trie *son[26];
Trie(){
ct=ct_son=0;
memset(son,0,sizeof(son));
}
};
Trie *root=new Trie;
void insert(Trie *nod, char *s) {
if(*s==0) {
++nod->ct;
return ;
}
if(nod->son[*s-'a']==0) {
++nod->ct_son;
nod->son[*s-'a']=new Trie;
}
insert(nod->son[*s-'a'],s+1);
}
bool erase(Trie *nod,char *s) {
if(*s==0)
--nod->ct;
else if(erase(nod->son[*s-'a'],s+1)) {
--nod->ct_son;
nod->son[*s-'a']=0;
}
if(nod->ct==0&&nod->ct_son==0&&nod!=root) {
delete nod;
return 1;
}
return 0;
}
int freq(Trie *nod,char *s) {
if(*s==0)
return nod->ct;
else {
if(nod->son[*s-'a']==0)
return 0;
else
return freq(nod->son[*s-'a'],s+1);
}
}
int lcp(Trie *nod,char *s) {
if(*s==0||nod->son[*s-'a']==0)
return 0;
return 1+lcp(nod->son[*s-'a'],s+1);
}
int main()
{
char v[20];
int x;
while(fscanf(si, "%i %s", &x, &v)!=EOF) {
if(x==0)
insert(root, v);
else if(x==1)
erase(root, v);
else if(x==2)
fprintf(so, "%i\n", freq(root, v));
else
fprintf(so, "%i\n", lcp(root, v));
}
return 0;
}