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