Pagini recente » Cod sursa (job #1853715) | Cod sursa (job #1011192) | Cod sursa (job #589820) | Cod sursa (job #2664709) | Cod sursa (job #1733647)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
using namespace std;
struct Node {
int npassing;
int nwords;
Node* children[26];
Node() {
npassing = nwords = 0;
memset(children, 0, sizeof(children));
}
};
void add(Node* node, char word[]) {
if (strlen(word) == 0)
return;
if (node->children[word[0] - 'a'] == 0)
node->children[word[0] - 'a'] = new Node;
node->children[word[0] - 'a']->npassing++;
if (strlen(word) == 1)
node->children[word[0] - 'a']->nwords++;
else
add(node->children[word[0] - 'a'], word + 1);
}
void delete_app(Node* node, char word[]) {
if (strlen(word) != 1)
delete_app(node->children[word[0] - 'a'], word + 1);
else
node->children[word[0] - 'a']->nwords--;
node->children[word[0] - 'a']->npassing--;
if(node->children[word[0] - 'a']->npassing == 0) {
delete node->children[word[0] - 'a'];
node->children[word[0] - 'a'] = 0;
}
}
int number_app(Node* node, char word[]) {
if (strlen(word) == 0 || node->children[word[0] - 'a'] == 0)
return 0;
if (strlen(word) == 1)
return node->children[word[0] - 'a']->nwords;
return number_app(node->children[word[0] - 'a'], word + 1);
}
int largest_prefix(Node* node, char word[]) {
if (strlen(word) == 0 || node->children[word[0] - 'a'] == 0)
return 0;
return 1 + largest_prefix(node->children[word[0] - 'a'], word + 1);
}
int main() {
int type;
char word[20];
Node* root = new Node;
ifstream fin("trie.in");
ofstream fout("trie.out");
while (fin >> type >> word) {
switch (type) {
case 0:
add(root, word);
break;
case 1:
delete_app(root, word);
break;
case 2:
fout << number_app(root, word) << '\n';
break;
case 3:
fout << largest_prefix(root, word) << '\n';
break;
}
}
return 0;
}