Pagini recente » Cod sursa (job #2658087) | Cod sursa (job #2819183) | Cod sursa (job #1107618) | Cod sursa (job #2423136) | Cod sursa (job #1775857)
#include "fstream"
#include "cstring"
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
const int ALPHABET = 26;
const int WORDMAX = 21;
class Node {
public:
Node() {
for(int i = 0 ; i < ALPHABET ; i++) {
children[i] = NULL;
}
partial = 0;
words = 0;
}
Node* children[ALPHABET + 1];
int partial;
int words;
};
Node* root = new Node();
void insert(Node* node, char* word) {
// fout << "Inserting: " << *word << "\n";
// fout.flush();
node->partial++;
if((*word) == '\0') {
node->words++;
return;
}
else {
if(node->children[*word - 'a'] == NULL) {
// fout << "New node!!!\n";
node->children[*word - 'a'] = new Node();
}
insert(node->children[*word - 'a'], ++word);
}
}
void remove(Node* node, char* word) {
// fout << "Removing: " << *word << "\n";
node->partial--;
if(*(word) == '\0') {
node->words--;
return;
}
else {
if(node->children[*word - 'a']->partial == 0) {
// fout << "Made NULL: " << (*word - 'a') << "\n";
node->children[*word - 'a'] = NULL;
}
else {
remove(node->children[*word - 'a'], ++word);
}
}
}
int count(Node* node, char* word) {
// fout << "Counting: " << *word << "\n";
// fout << "Counting next: " << *(word + 1) << "\n";
// fout << "Is equal? : " << (*(word + 1) == '\0') << "\n";
fout.flush();
if(*(word) == '\0') {
// fout << "In terminating if condition node is: " << node << "\n";
// fout.flush();
// fout << "From count, returning: " << node->words << "\n";
// fout.flush();
return node->words;
}
else {
if(node->children[*word - 'a'] == NULL) {
return 0;
}
else {
return count(node->children[*word - 'a'], ++word);
}
}
}
int prefix(Node* node, char* word, int occurences, int currentLevel) {
// fout << "Prefix: " << *word << "\n";
// fout.flush();
if(*(word + 1) == '\0') {
return currentLevel;
}
else {
if(node->children[*word - 'a'] == NULL || node->children[*word - 'a']->partial - occurences == 0) {
return currentLevel;
}
else {
return prefix(node->children[*word - 'a'], ++word, occurences, currentLevel + 1);
}
}
}
int main() {
while(!fin.eof()) {
int type;
char word[WORDMAX];
memset(word, 0, WORDMAX);
fin >> type >> word;
if(strlen(word) == 0) {
//in case of empty line
break;
}
word[strlen(word)] = '\0';
// fout << "Word: " << word << "\n";
// fout << "strlen(word): " << strlen(word) << "\n";
// fout.flush();
if(type == 0) {
insert(root, word);
}
else if(type == 1) {
remove(root, word);
}
else if(type == 2) {
// fout << "type 2\n";
fout << count(root, word) << "\n";
// fout.flush();
}
else {
int occurences = count(root, word);
// fout << "occurences: " << occurences << "\n";
// fout.flush();
fout << prefix(root, word, occurences, 0) << "\n";
// fout.flush();
}
}
}