Pagini recente » Istoria paginii utilizator/cupadorinel | Cod sursa (job #1666247) | Statistici Halmagean Iulian (hiulian) | Monitorul de evaluare | Cod sursa (job #1707034)
#include<fstream>
#include<iostream>
#include<string>
#include<cstring>
#include <sstream>
using namespace std;
struct TrieNode {
int count;
int childrenCount;
TrieNode* children[28];
TrieNode() {
count = 0;
childrenCount = 0;
memset(children, 0, sizeof(children));
}
};
void addWord(TrieNode* root, string word) {
//
if (word.length() == 0) {
root->count++;
return;
}
char first = word.at(0);
if (!root->children[first - 'a']) {
root->childrenCount++;
root->children[first - 'a'] = new TrieNode();
}
word = word.substr(1);
addWord(root->children[first - 'a'], word);
}
int queryWordCount(TrieNode* root, string word) {
//
if (word.length() == 0) {
return root->count;
}
char first = word.at(0);
word = word.substr(1);
if (root->children[first - 'a']) {
return queryWordCount(root->children[first - 'a'], word);
} else {
return 0;
}
}
bool deleteWord(TrieNode* root, string word) {
//
if (word.length() == 0) {
root->count--;
} else {
char first = word.at(0);
word = word.substr(1);
bool propagation = deleteWord(root->children[first - 'a'], word);
if (propagation) {
root->childrenCount--;
}
}
if (root->childrenCount == 0 && root->count == 0) {
delete root;
return true;
}
return false;
}
int queryLongestPrefix(TrieNode *root, string word) {
//
if (word.length() == 0) {
return 0;
}
char first = word.at(0);
word = word.substr(1);
if (root && root->children[first-'a']) {
return 1 + queryLongestPrefix(root->children[first-'a'], word);
} else {
return 0;
}
}
int main() {
//
TrieNode root;
ifstream f("trie.in");
ofstream g("trie.out");
string line;
int opType;
while (f >> opType) {
string opValue;
f >> opValue;
switch (opType) {
case 0:
addWord(&root, opValue);
break;
case 1:
deleteWord(&root, opValue);
break;
case 2:
g << queryWordCount(&root, opValue) << "\n";
break;
case 3:
g << queryLongestPrefix(&root, opValue) << "\n";
}
}
}