Pagini recente » Cod sursa (job #2338535) | Cod sursa (job #1277297) | Cod sursa (job #1132519) | Cod sursa (job #1383724) | Cod sursa (job #1597587)
#include<bits/stdc++.h>
#define in f
#define out g
#define SIGMA 26
#define ascii (int)'a'
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
class Trie {
private:
Trie* children[SIGMA];
int value = 0;
int count = 0;
public:
void insert(string word) {
if(word.size() == 0) {
this->count++;
return;
}
if(children[word[0] - ascii] == NULL) {
children[word[0] - ascii] = new Trie();
}
children[word[0] - ascii]->value++;
children[word[0] - ascii]->insert(word.substr(1));
}
int find(string word) {
if(word.size() == 0) {
return this->count;
}
if(children[word[0] - ascii] == false || children[word[0] - ascii]->value == 0) {
return 0;
} else return children[word[0] - ascii]->find(word.substr(1));
}
void erase(string word) {
if(word.size() == 0) {
this->count--;
return;
}
if(children[word[0] - ascii]) {
children[word[0] - ascii]->value--;
if(children[word[0] - ascii]->value == 0) {
delete(children[word[0] - ascii]);
return;
} else children[word[0] - ascii]->erase(word.substr(1));
}
}
int longestPrefix(string word) {
return longestPrefix(word, 0);
}
int longestPrefix(string word, int length) {
if(word.size() == 0) {
return length;
}
if(children[word[0] - ascii] == false || children[word[0] - ascii]->value == 0) {
return length;
} else return children[word[0] - ascii]->longestPrefix(word.substr(1), length + 1);
}
};
int main() {
Trie* trie = new Trie();
int operation;
string word;
while(in >> operation) {
in >> word;
switch(operation) {
case 0:
trie->insert(word);
break;
case 1:
trie->erase(word);
break;
case 2:
out << trie->find(word) << "\n";
break;
case 3:
out << trie->longestPrefix(word) << "\n";
break;
}
}
return 0;
}