Pagini recente » Cod sursa (job #524619) | Cod sursa (job #1821823) | Cod sursa (job #108141) | Cod sursa (job #255) | Cod sursa (job #2856454)
#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 (true){
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';
if (fin.eof())
return 0;
}
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->nr == 0){
int x;
while (ct->nr == 0 && ct->c != 0 && ct->pr < 2){
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){
break;
}
Nr++;
ct = ct->a[ch-97];
}
return Nr;
}