Pagini recente » Cod sursa (job #888642) | Cod sursa (job #340337) | Cod sursa (job #3140478) | Cod sursa (job #586530) | Cod sursa (job #1992865)
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
using namespace std;
class TrieNode {
public:
// Initialize your data structure here.
int nrfii;
bool endOfWord;
int count;
TrieNode *fiu[26];
TrieNode() {
nrfii = 0;
count = 0;
endOfWord = false;
memset(fiu, 0, sizeof(fiu));
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insHelper(TrieNode *root, string word, int i) {
if (i == word.length()) {
root->endOfWord = true;
return;
}
if (!root->fiu[word[i] - 'a']) {
root->fiu[word[i] - 'a'] = new TrieNode;
root->nrfii ++;
}
root->fiu[word[i] - 'a']->count ++;
insHelper(root->fiu[word[i] - 'a'], word, i + 1);
}
// Inserts a word into the trie.
void insert(string word) {
insHelper(root, word, 0);
}
void delHelper(TrieNode *root, string word, int i) {
if (i == word.length()) {
if (root->count == 0) {
root->endOfWord = false;
}
return;
}
if (root->fiu[word[i] - 'a']) {
delHelper(root->fiu[word[i] - 'a'], word, i + 1);
root->fiu[word[i] - 'a']->count --;
if (root->fiu[word[i] - 'a']->count == 0) {
root->fiu[word[i] - 'a'] = NULL;
root->nrfii --;
}
}
}
void deleter(string word) {
delHelper(root, word, 0);
}
int searcHelper(TrieNode *root, string word, int i) {
if (i == word.length() && root->endOfWord)
return root->count;
if (root->fiu[word[i] - 'a'])
return searcHelper(root->fiu[word[i] - 'a'], word, i + 1);
return 0;
}
// Returns if the word is in the trie.
int search(string word) {
return searcHelper(root, word, 0);
}
int preHelper(TrieNode *root, string prefix, int i) {
if (i == prefix.length()) {
return prefix.length();
} else if (!root->fiu[prefix[i] - 'a']) {
return i;
} else return preHelper(root->fiu[prefix[i] - 'a'], prefix, i + 1);
}
// Returns if there is any word in the trie
// that starts with the given prefix.
int prefixed(string prefix) {
return preHelper(root, prefix, 0);
}
private:
TrieNode* root;
};
int main() {
ifstream ifs;
ifs.open("trie.in", std::ifstream::in);
ofstream ofs;
ofs.open("trie.out", std::ofstream::out);
Trie trie;
int operation;
string word;
while (true) {
getline(ifs, word);
if (ifs.eof())
break;
operation = word[0] - '0';
word = word.substr(2, string::npos);
if (operation == 0) {
trie.insert(word);
} else if (operation == 1) {
trie.deleter(word);
} else if (operation == 2) {
int sol = trie.search(word);
ofs << sol << '\n';
} else if (operation == 3) {
int sol = trie.prefixed(word);
ofs << sol << '\n';
}
}
return 0;
}