Pagini recente » Cod sursa (job #2628726) | Cod sursa (job #754298) | Cod sursa (job #2263524) | Cod sursa (job #45120) | Cod sursa (job #1117882)
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
#define ALF 26
struct node {
int nrChild, key;
node* next[ALF];
node() {
nrChild = key = 0;
memset(next, 0, sizeof(next));
}
};
FILE* f = fopen("trie.in", "r");
FILE* g = fopen("trie.out", "w");
node root;
char buf[25];
void add(node* ptr, char* c)
{
while (*c != '\n') {
if (ptr->next[*c - 'a'] == 0) {
ptr->next[*c - 'a'] = new node;
ptr->nrChild++;
}
ptr = ptr->next[*c - 'a'];
c++;
}
ptr->key++;
}
bool del(node* ptr, char* c)
{
if (*c == '\n') {
ptr->key--;
} else if (del(ptr->next[*c - 'a'], c + 1) == true) {
ptr->next[*c - 'a'] = 0;
ptr->nrChild--;
}
if (ptr->key == 0 && ptr->nrChild == 0 && ptr != &root) {
delete ptr;
return true;
}
return false;
}
int numAparitions(node* ptr, char* c)
{
while (*c != '\n') {
if (ptr->next[*c - 'a'] == 0) {
return 0;
}
ptr = ptr->next[*c - 'a'];
c++;
}
return ptr->key;
}
int maxPrefix(node* ptr, char* c)
{
int nr = 0;
while (*c != '\n' && ptr->next[*c - 'a'] != 0) {
ptr = ptr->next[*c - 'a'];
nr++, c++;
}
return nr;
}
int main()
{
while (fgets(buf, sizeof(buf), f)) {
switch (buf[0]) {
case '0': add(&root, buf + 2); break;
case '1': del(&root, buf + 2); break;
case '2': fprintf(g, "%d\n", numAparitions(&root, buf + 2)); break;
case '3': fprintf(g, "%d\n", maxPrefix(&root, buf + 2));
}
}
}