Pagini recente » Istoria paginii runda/learnhouse_10/clasament | Cod sursa (job #1707027)
#include<fstream>
#include<iostream>
#include<string>
#include <sstream>
using namespace std;
struct TrieNode {
int count;
int childrenCount;
TrieNode* children[26];
TrieNode() {
count = 0;
childrenCount = 0;
for(int it = 0; it < 26; it++) {
children[it] = 0;
}
}
};
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;
}
}
TrieNode* deleteWord(TrieNode* root, string word) {
//
if (word.length() == 0) {
root->count--;
} else {
char first = word.at(0);
word = word.substr(1);
root->children[first - 'a'] = deleteWord(root->children[first - 'a'], word);
if (!root->children[first - 'a']) {
root->childrenCount--;
}
}
if (root->childrenCount == 0 && root->count == 0) {
delete root;
return 0;
}
return root;
}
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;
while (getline(f, line)) {
int opType;
string opValue;
istringstream linestream(line);
linestream >> opType >> 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";
}
}
}