Pagini recente » Cod sursa (job #918430) | Cod sursa (job #1176664) | Cod sursa (job #1446604) | Cod sursa (job #1125873) | Cod sursa (job #1502398)
#include <stdio.h>
#include <vector>
#define MAXALF 26
using namespace std;
struct nodeTrie {
int nr, nrDown;
nodeTrie *sons[MAXALF];
nodeTrie() {
nr = nrDown = 0;
for(int i = 0; i < MAXALF; i++)
sons[i] = NULL;
}
} *root;
int type;
char w[30];
void add(char s[]) {
nodeTrie *p = root;
for(int i = 0; s[i] != '\0'; i++) {
p -> nrDown ++;
int x = s[i] - 'a';
if(p -> sons[x] == NULL)
p -> sons[x] = new nodeTrie();
p = p -> sons[x];
}
p -> nr ++;
p -> nrDown ++;
}
void del(char s[]) {
nodeTrie *p = root;
pair<nodeTrie *, int> last = make_pair((nodeTrie *) NULL, 0);
int i;
vector<nodeTrie *> v;
for(i = 0; s[i] != '\0'; i++) {
int x = s[i] - 'a';
if(-- p -> nrDown == 0 && p != root) v.push_back(p);
if(last.first == NULL && p -> sons[x] -> nrDown - 1 == 0) last = make_pair(p, x);
p = p -> sons[x];
}
p -> nr --, p -> nrDown --;
if(p -> nrDown == 0) v.push_back(p);
while(!v.empty()) {
p = v.back(); v.pop_back();
delete(p);
}
if(last.first != NULL) last.first -> sons[last.second] = NULL;
}
int countAp(char s[]) {
nodeTrie *p = root;
int i;
for(i = 0; s[i] != '\0'; i++) {
int x = s[i] - 'a';
if((p = p -> sons[x]) == NULL) return 0;
}
return p -> nr;
}
int query(char s[]) {
nodeTrie *p = root;
int ans = 0, i;
for(i = 0; s[i] != '\0'; i++, ans++) {
int x = s[i] - 'a';
if((p = p -> sons[x]) == NULL) return ans;
}
return ans;
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
root = new nodeTrie();
while(scanf("%d %s\n", &type, w) == 2) {
switch(type) {
case 0: add(w); break;
case 1: del(w); break;
case 2: printf("%d\n", countAp(w)); break;
case 3: printf("%d\n", query(w));
}
}
}