Pagini recente » Cod sursa (job #1202002) | Cod sursa (job #347345) | Rating Pletosu Cosmin-Andrei (Pleto) | Cod sursa (job #9768) | Cod sursa (job #3296774)
#include <fstream>
#include <string>
#include <stack>
using namespace std;
struct trieNode {
trieNode* c[26];
int occurrences;
trieNode() {
occurrences = 0;
for(int i = 0; i < 26; i++) {
c[i] = NULL;
}
}
};
bool isEmpty(trieNode* node) {
for(int i = 0; i < 26; i++) {
if(node->c[i] != NULL) return false;
}
return true;
}
int getNumOfChildren(trieNode* node) {
int nr = 0;
for(int i = 0; i < 26; i++) {
if(node->c[i] != NULL) nr++;
}
return nr;
}
trieNode* insert(trieNode* root, string &str) {
trieNode* current = root;
for(char ch: str) {
if(current->c[ch - 'a'] == NULL) {
current->c[ch - 'a'] = new trieNode();
current = current->c[ch - 'a'];
} else {
current = current->c[ch - 'a'];
}
}
current->occurrences += 1;
return current;
}
void remove(trieNode* root, string &str) {
stack<trieNode*> nodes;
nodes.push(root);
for(char ch: str) {
if(nodes.top()->c[ch - 'a'] == NULL) return;
nodes.push(nodes.top()->c[ch - 'a']);
}
nodes.top()->occurrences -= 1;
while(!nodes.empty() && isEmpty(nodes.top()) && nodes.top()->occurrences == 0) {
trieNode* top = nodes.top();
delete(top);
nodes.pop();
nodes.top()->c[str[nodes.size()-1] - 'a'] = NULL;
}
}
trieNode* search(trieNode* root, string &str) {
trieNode* current = root;
for(char ch: str) {
if(current->c[ch - 'a'] == NULL) return NULL;
current = current->c[ch - 'a'];
}
return current;
}
bool isPrefix(trieNode* root, string &str) {
trieNode* node = search(root, str);
if(node == NULL) return false;
return true;
}
int getOccurences(trieNode* root, string &str) {
trieNode* node = search(root, str);
if(node == NULL) return false;
return node->occurrences;
}
int longestCommonPrefix(trieNode* root, string &str) {
trieNode* current = root;
int lcp = 0;
for(char ch: str) {
if(current->c[ch - 'a'] == NULL) break;
current = current->c[ch - 'a'];
lcp++;
}
return lcp;
}
ifstream fin("trie.in");
ofstream fout("trie.out");
int main() {
trieNode* rootTrie = new trieNode();
int op;
string cuv;
while(fin >> op) {
fin >> cuv;
switch (op)
{
case 0:
insert(rootTrie, cuv);
break;
case 1:
remove(rootTrie, cuv);
break;
case 2:
fout << getOccurences(rootTrie, cuv) << "\n";
break;
case 3:
fout << longestCommonPrefix(rootTrie, cuv) << "\n";
}
}
}