Pagini recente » Cod sursa (job #2976231) | Cod sursa (job #1212350) | Cod sursa (job #1477782) | Cod sursa (job #1355542) | Cod sursa (job #613535)
Cod sursa(job #613535)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ch (*s-'a')
using namespace std;
int i,n,m;
typedef struct trie {
trie *f[26];
int cnt, nr;
trie () {
cnt=nr=0;
memset(f,0,sizeof(f));
}
};
trie *T=new trie;
char q[30];
void inserare(trie *nod,char *s) {
if (*s<'a' || *s>'z') {
nod->cnt++;
return;
}
if (nod->f[ch]==0) {
nod->f[ch]=new trie;
nod->nr++;
}
inserare(nod->f[ch],s+1);
}
int sterge(trie *nod,char *s) {
if (*s<'a' || *s>'z') nod->cnt--;
else
if (sterge(nod->f[ch],s+1)) {
nod->f[ch]=0;
nod->nr--;
}
if (nod->cnt==0 && nod->nr==0 && nod!=T) {
delete nod;
return 1;
}
return 0;
}
int aparitie(trie *nod, char *s) {
if (*s<'a' || *s>'z')
return nod->cnt;
if (nod->f[ch])
return aparitie(nod->f[ch],s+1);
return 0;
}
int prefix(trie *nod, char *s, int k) {
if ((*s<'a' || *s>'z') || nod->f[ch]==0)
return k;
else
return prefix(nod->f[ch],s+1,k+1);
}
int main () {
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
while (!feof(stdin)) {
gets(q);
if (q[0]!=0) {
if (q[0]=='0') inserare(T,q+2);
else
if (q[0]=='1') sterge(T,q+2);
else
if (q[0]=='2') printf("%d\n",aparitie(T,q+2));
else
printf("%d\n",prefix(T,q+2,0));
}
}
return 0;
}