Pagini recente » Cod sursa (job #1435610) | Cod sursa (job #2587492) | Cod sursa (job #448101) | Cod sursa (job #496342) | Cod sursa (job #1613723)
#include <iostream>
#include <stdio.h>
#include <cstring>
#define MAX 32
#define C *c - 'a'
using namespace std;
char l[MAX];
char *x = l;
FILE *fin;
FILE *fout;
struct trie {
int am;
int dim;
int cnt;
trie *m[26];
trie() {
am = dim = cnt = 0;
memset(m, 0, sizeof(m));
}
};
trie *r;
void ins(trie *root, char *c) {
int a = *c-'a';
if(*c == '\n') {
root->cnt++;
return;
}
if(root->m[a] == 0) {
root->m[a] = new trie();
root->dim++;
}
ins(root->m[a], c+1);
}
bool del(trie *root, char *c) {
int a = *c-'a';
if(*c == '\n') {
root->cnt--;
return 1;
}
if(del(root->m[a], c+1)) {
root->m[a] = 0;
root->dim--;
}
if(root->cnt == 0 && root->dim == 0 && root != r) {
delete root;
return true;
}
return false;
}
int ap(trie *root, char *c) {
int a = *c-'a';
if(*c == '\n')
return root->cnt;
if(root->m[a] == 0)
return 0;
return ap(root->m[a], c+1);
}
int pref(trie *root, char *c, int crr) {
char a = *c-'a';
if(*c == '\n' || root->m[a] == 0)
return crr;
return pref(root->m[a], c+1, crr+1);
}
int main() {
fin = fopen("trie.in", "r");
fout = fopen("trie.out", "w");
int t;
char *wa;
r = new trie();
fgets(x, MAX, fin);
while(!feof(fin)) {
if(x[0] == '0')
ins(r, x+2);
else if(x[0] == '1')
del(r, x+2);
else if(x[0] == '2')
fprintf(fout, "%d\n", ap(r, x+2));
else if(x[0] == '3')
fprintf(fout, "%d\n", pref(r, x+2, 0));
x=l;
fgets(x, MAX, fin);
}
return 0;
}