Pagini recente » Cod sursa (job #1352627) | Cod sursa (job #1387121) | Cod sursa (job #1672931) | Cod sursa (job #2376957) | Cod sursa (job #1527355)
#include <cstdio>
#include <cstring>
using namespace std;
struct Trie {
int cnt, nr_fii;
Trie *son[26];
Trie() {
cnt = nr_fii = 0;
memset(son, 0 ,sizeof(son));
}
};
Trie *T = new Trie;
char line[23];
void ins(Trie *nod, char *s) {
if (*s == '\n') {
nod->cnt++;
return;
}
if (nod->son[*s - 97] == 0) {
nod->son[*s - 97] = new Trie;
nod->nr_fii++;
}
ins(nod->son[*s - 97], s + 1);
}
int del(Trie *nod, char *s){
if (*s == '\n')
nod->cnt--;
else
if (del(nod->son[*s - 97], s + 1)) {
nod->son[*s - 97] = 0;
nod->nr_fii--;
}
if (nod->cnt == 0 && nod->nr_fii == 0 && nod != T) {
delete nod;
return 1;
}
return 0;
}
int freq(Trie *nod, char *s) {
if (*s == '\n')
return nod->cnt;
if (nod->son[*s - 97])
return freq(nod->son[*s - 97], s + 1);
return 0;
}
int prefix(Trie *nod, char *s, int k) {
if (*s == '\n' or nod->son[*s - 97] == 0)
return k;
return prefix(nod->son[*s - 97], s + 1, k + 1);
}
int main() {
freopen( "trie.in", "r", stdin );
freopen( "trie.out", "w", stdout );
fgets( line, 23, stdin );
while( !feof( stdin ) ) {
switch( line[0] ) {
case '0': ins( T, line+2 ); break;
case '1': del( T, line+2 ); break;
case '2': printf( "%d\n", freq( T, line+2 ) ); break;
case '3': printf( "%d\n", prefix( T, line+2, 0 ) ); break;
}
fgets( line, 32, stdin );
}
return 0;
}