Pagini recente » Cod sursa (job #903968) | Cod sursa (job #887944) | Cod sursa (job #1445079) | Cod sursa (job #2331798) | Cod sursa (job #2854289)
#include <iostream>
#include <cstdio>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
//ifstream f("trie.in");
ofstream g("trie.out");
struct trie {
int cnt, nrfii;
trie *a[26];
trie() {
cnt = nrfii = 0;
memset(a, 0, sizeof(a));
}
};
trie *T = new trie;
void ins(trie *nod, char *s) {
if(*s == '\n') {
nod -> cnt ++;
return;
}
if(nod -> a[*s - 'a'] == 0) {
nod -> a[*s - 'a'] = new trie;
nod -> nrfii ++;
}
ins(nod -> a[*s - 'a'], s + 1);
}
int del(trie *nod, char *s) {
if(*s == '\n')
nod -> cnt --;
else if(del(nod -> a[*s - 'a'], s + 1)) {
nod -> a[*s - 'a'] = 0;
nod -> nrfii --;
}
if(nod -> cnt == 0 && nod -> nrfii == 0 && nod != T) {
delete nod;
return 1;
}
return 0;
}
int que(trie *nod, char *s) {
if(*s == '\n')
return nod -> cnt;
if(nod -> a[*s - 'a']) {
return que(nod -> a[*s - 'a'], s + 1);
}
return 0;
}
int pre(trie *nod, char *s, int k) {
if(*s == '\n' || nod -> a[*s - 'a'] == 0)
return k;
return pre(nod -> a[*s - 'a'], s + 1, k + 1);
}
int main()
{
freopen("trie.in", "r", stdin);
char line[32];
//f.get(line, 32);
fgets(line, 32, stdin);
while(!feof(stdin)) {
//line[strlen(line)] = '\n';
//g << line;
switch(line[0]) {
case '0': ins(T, line + 2); break;
case '1': del(T, line + 2); break;
case '2': g << que(T, line + 2) << '\n'; break;
case '3': g << pre(T, line + 2, 0) << '\n'; break;
}
//f.get(line, 32);
fgets(line, 32, stdin);
}
//f.close();
g.close();
return 0;
}