Pagini recente » Cod sursa (job #2107252) | Cod sursa (job #1371161) | Cod sursa (job #277244) | Cod sursa (job #316673) | Cod sursa (job #1117577)
#include <cstring>
#include <iostream>
#include <fstream>
using namespace std;
#define ALF 27
struct node {
int key, nrChild;
node* child[ALF];
node() {
key = nrChild = 0;
memset(child, 0, sizeof(child));
}
};
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->child[*c - 'a'] == 0) {
ptr->child[*c - 'a'] = new node;
ptr->nrChild++;
}
ptr = ptr->child[*c - 'a'];
c++;
}
ptr->key++;
}
bool del(node* ptr, char* c)
{
if (*c == '\n') {
ptr->key--;
} else if (del(ptr->child[*c - 'a'], c + 1) == true) {
ptr->child[*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->child[*c - 'a'] == 0) {
return 0;
}
ptr = ptr->child[*c - 'a'];
c++;
}
return ptr->key;
}
int longestPrefix(node* ptr, char* c)
{
int nr = 0;
while (*c != '\n' && ptr->child[*c - 'a'] != 0) {
ptr = ptr->child[*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", longestPrefix(&root, buf + 2)); break;
}
}
fclose(f);
fclose(g);
return 0;
}