Pagini recente » Cod sursa (job #2090864) | Rating Traian Basescu (basescu69) | Cod sursa (job #92072) | Istoria paginii runda/sim3/clasament | Cod sursa (job #1707038)
#include<fstream>
#include<iostream>
#include<string>
#include<cstring>
#include <sstream>
using namespace std;
string word;
struct TrieNode {
int count;
int childrenCount;
TrieNode* children[28];
TrieNode() {
count = 0;
childrenCount = 0;
memset(children, 0, sizeof(children));
}
};
void addWord(TrieNode* root, int pos) {
//
if (word.length() == pos) {
root->count++;
return;
}
char first = word.at(pos);
if (!root->children[first - 'a']) {
root->childrenCount++;
root->children[first - 'a'] = new TrieNode();
}
addWord(root->children[first - 'a'], pos + 1);
}
int queryWordCount(TrieNode* root, int pos) {
//
if (word.length() == pos) {
return root->count;
}
char first = word.at(pos);
if (root->children[first - 'a']) {
return queryWordCount(root->children[first - 'a'], pos + 1);
} else {
return 0;
}
}
TrieNode* deleteWord(TrieNode* root, int pos) {
//
if (word.length() == pos) {
root->count--;
} else {
char first = word.at(pos);
root->children[first - 'a'] = deleteWord(root->children[first - 'a'], pos + 1);
if (!root->children[first - 'a']) {
root->childrenCount--;
}
}
if (root->childrenCount == 0 && root->count == 0) {
delete root;
return 0;
}
return root;
}
int queryLongestPrefix(TrieNode *root, int pos) {
//
if (word.length() == pos) {
return 0;
}
char first = word.at(pos);
if (root && root->children[first-'a']) {
return 1 + queryLongestPrefix(root->children[first-'a'], pos + 1);
} 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 >> word;
switch (opType) {
case 0:
addWord(&root, 0);
break;
case 1:
deleteWord(&root, 0);
break;
case 2:
g << queryWordCount(&root, 0) << "\n";
break;
case 3:
g << queryLongestPrefix(&root, 0) << "\n";
break;
}
}
}