Pagini recente » Cod sursa (job #466162) | Cod sursa (job #466596) | Cod sursa (job #1815576) | Cod sursa (job #1220485) | Cod sursa (job #1427108)
#include <fstream>
#include <vector>
#include <string.h>
#include <stdlib.h>
using namespace std;
class Node {
public:
vector<Node *> neighbours;
int freq, branches;
Node() : neighbours(26, NULL), freq(0), branches(0) {}
~Node() {}
void insert(char * word) {
if (*word == '\0') {
++freq;
return;
}
int index = word[0] - 'a';
if (neighbours[index] == NULL) {
neighbours[index] = new Node();
++branches;
}
neighbours[index]->insert(word + 1);
}
bool remove(char * word) {
int index = word[0] - 'a';
if (*word == '\0') {
--freq;
} else if (neighbours[index] != NULL) {
if (neighbours[index]->remove(word + 1)) {
delete neighbours[index];
neighbours[index] = NULL;
--branches;
}
} else {
return false;
}
return freq == 0 && branches == 0;
}
int frequency(char * word) {
if (*word == '\0') {
return freq;
}
int index = word[0] - 'a';
if (neighbours[index] != NULL) {
return neighbours[index]->frequency(word + 1);
} else {
return 0;
}
}
int longestPrefix(char * word, int length) {
if (*word == '\0' || neighbours[word[0] - 'a'] == NULL)
return length;
int index = word[0] - 'a';
return neighbours[index]->longestPrefix(word + 1, length + 1);
}
};
ifstream fin("trie.in");
ofstream fout("trie.out");
Node * root;
string word;
int op;
char * w;
int main() {
root = new Node();
while (true) {
fin >> op >> word;
w = strdup(word.c_str());
if (fin.eof())
break;
if (op == 0) {
root->insert(w);
} else if (op == 1) {
root->remove(w);
} else if (op == 2) {
fout << root->frequency(w) << '\n';
} else if (op == 3) {
fout << root->longestPrefix(w, 0) << '\n';
}
free(w);
}
return 0;
}