Pagini recente » Cod sursa (job #2266974) | Cod sursa (job #671056) | Cod sursa (job #273545) | Cod sursa (job #1886971) | Cod sursa (job #1910768)
#include <iostream>
#include <fstream>
#include <cstring>
#define SMAX 25
#define SIGMAR 30
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
char s[SMAX];
struct Nod {
int cnt;
Nod *sons[SIGMAR];
Nod *tata;
int poz;
Nod () {
memset(sons, 0, sizeof(sons));
cnt = 0;
tata = 0;
poz = 26;
}
};
Nod *root = new Nod();
void insert (Nod *root, char *s) {
if (!*s) {
root->cnt += 1;
}
else {
int son = *s - 'a';
if (!root->sons[son]) {
root->sons[son] = new Nod();
root->sons[son]->tata = root;
root->sons[son]->poz = son;
}
insert(root->sons[son], s+1);
}
}
void del (Nod *root, char *s) {
if (!*s) {
root->cnt -= 1;
if (root -> cnt == 0) {
root->tata->sons[root->poz] = 0;
delete root;
}
}
else {
int son = *s - 'a';
if (!root->sons[son]) {
return;
}
del(root->sons[son], s+1);
bool ok = 0;
for (int i = 0; i < 26; ++i) {
if (root->sons[i] != 0) {
ok = 1;
i = 26;
}
}
if (!ok) {
root->tata->sons[root->poz] = 0;
delete root;
}
}
}
int dfs (Nod *root, char *s) {
if (!*s) {
//cout << root->cnt;
int ret = root->cnt;
//cout << ret;
return ret;
}
else {
int son = *s - 'a';
if (!root->sons[son]) {
return 0;
}
dfs(root->sons[son], s+1);
}
//return 0;
}
void afis (Nod *root, int level) {
for (int i = 0; i < 26; ++i) {
if (!root->sons[i]) {
continue;
}
for (int j = 1; j <= level; ++j) {
cout << " ";
}
char c = i + 'a';
cout << c << " " << root->sons[i]->cnt << endl;
afis(root->sons[i], level+1);
}
}
int prefix (Nod *root, char *s) {
int ret = 0;
for (int i = 0; i < 26; ++i) {
if (!root->sons[i]) {
continue;
}
char c = i + 'a';
if (*s == c) {
ret = 1 + prefix(root->sons[i], s+1);
}
}
return ret;
}
int main ()
{
while (fin.getline(s, SMAX)) {
if (s[0] == '0') {
insert(root, s+2);
}
else
if (s[0] == '1') {
del(root, s+2);
}
else
if (s[0] == '2') {
fout << dfs(root, s+2) << endl;
}
else {
fout << prefix(root, s+2) << endl;
}
/*afis(root,0);
cout << endl;*/
}
//afis(root,0);
fin.close();
fout.close();
return 0;
}