Pagini recente » Cod sursa (job #2870226) | Cod sursa (job #2857276)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
struct trie{
char c; int nr = 0, pr = 0;
trie* a[26]; trie* bac;
};
int n, m;
void add(string &st, trie* t);
void del(string &st, trie* t);
int nr_ap(string &st, trie* t);
int cmlp(string &st, trie* t);
int main(){
int x; string st;
trie *t = new trie();
while (fin >> x >> st){
if (x == 0)
add(st, t);
if (x == 1)
del(st, t);
if (x == 2)
fout << nr_ap(st, t) << '\n';
if (x == 3)
fout << cmlp(st, t) << '\n';
}
return 0;
}
void add(string &st, trie* t){
trie* ct = t;
for (const char &ch : st){
if (ct->a[ch-97] == NULL){
ct->a[ch-97] = new trie();
ct->a[ch-97]->c = ch;
ct->a[ch-97]->bac = ct;
ct->pr++;
}
ct = ct->a[ch-97];
}
ct->nr++;
}
int nr_ap(string &st, trie* t){
trie* ct = t;
for (const char &ch : st){
if (ct->a[ch-97] == NULL)
return 0;
ct = ct->a[ch-97];
}
return ct->nr;
}
void del(string &st, trie* t){
trie* ct = t;
for (const char &ch : st){
if (ct->a[ch-97] == NULL)
return;
ct = ct->a[ch-97];
}
ct->nr--;
if (ct->pr > 0)
return;
if (ct->nr == 0){
int x;
while (ct->nr == 0 && ct->pr < 2){
ct->pr = 0;
x = ct->c;
ct = ct->bac;
ct->a[x-97] = NULL;
free (ct->a[x-97]);
}
}
return;
}
int cmlp(string &st, trie* t){
trie* ct = t; int Nr = 0;
for (const char &ch : st){
if (ct->a[ch-97] == NULL || ct->pr < 1){
break;
}
Nr++;
ct = ct->a[ch-97];
}
return Nr;
}