Pagini recente » Monitorul de evaluare | Cod sursa (job #613969) | Cod sursa (job #1464468) | Cod sursa (job #1097484) | Cod sursa (job #1293880)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
#include <stack>
#include <iostream>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <sstream>
#include <algorithm>
#include <exception>
using namespace std;
struct Trie{
int num_words, num_prefixes;
struct Trie* next[26];
Trie() {
num_words = num_prefixes = 0;
for (int i = 0; i < 26; i++) {
next[i] = NULL;
}
}
void add_word(string s) {
Trie* root = this;
int next_char;
for (int i = 0; i < s.length(); i++) {
next_char = s[i] - 'a';
if (root->next[next_char] == NULL) {
root->next[next_char] = new Trie();
}
root = root->next[next_char];
root->num_prefixes++;
}
root->num_words++;
}
void rem_word(string s) {
Trie* root = this;
int next_char;
for (int i = 0; i < s.length(); i++) {
next_char = s[i] - 'a';
if (root->next[next_char] == NULL) {
root->next[next_char] = new Trie();
}
root = root->next[next_char];
root->num_prefixes--;
}
root->num_words--;
}
int num_of_occurances(string s) {
Trie* root = this;
int next_char;
for (int i = 0; i < s.length(); i++) {
next_char = s[i] - 'a';
if (root->next[next_char] == NULL) {
return 0;
}
root = root->next[next_char];
}
return root->num_words;
}
int longest_common_prefix(string s) {
Trie* root = this;
int next_char, longest_prefix = 0;
for (int i = 0; i < s.length(); i++) {
next_char = s[i] - 'a';
if (root->next[next_char] == NULL) {
return longest_prefix;
}
root = root->next[next_char];
if (root->num_prefixes == 0) {
return longest_prefix;
}
longest_prefix++;
}
return longest_prefix;
}
};
int n;
string s;
int main() {
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
Trie *root = new Trie();
while (cin >> n >> s) {
switch(n) {
case 0: root->add_word(s); break;
case 1: root->rem_word(s); break;
case 2: printf("%d\n", root->num_of_occurances(s)); break;
case 3: printf("%d\n", root->longest_common_prefix(s)); break;
}
}
return 0;
}