Pagini recente » Cod sursa (job #234247) | Cod sursa (job #1419930) | Cod sursa (job #2832036) | Cod sursa (job #2847607) | Cod sursa (job #2567144)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
using namespace std;
const int LITMAX = 21;
struct Trie {
int nwords, fr;
Trie* son[LITMAX];
Trie() {
nwords = fr = 0;
for(int i = 0; i < LITMAX; i ++)
son[i] = NULL;
}
};
void addTrie(string &s, int pos, Trie* root) {
root -> nwords ++;
if(pos == s.size()) {
root -> fr ++;
return;
}
int c = s[pos] - 'a';
if(root -> son[c] == NULL)
root -> son[c] = new Trie();
addTrie(s, pos + 1, root -> son[c]);
}
void delTrie(string &s, int pos, Trie* root) {
root -> nwords --;
if(pos == s.size()) {
root -> fr --;
return;
}
int c = s[pos] - 'a';
delTrie(s, pos + 1, root -> son[c]);
}
int freq(string &s, int pos, Trie* root) {
if(pos == s.size())
return root -> fr;
int c = s[pos] - 'a';
if(root -> son[c] == NULL)
return 0;
return freq(s, pos + 1, root -> son[c]);
}
int prefix(string &s, int pos, Trie* root) {
if(pos == s.size())
return 0;
int c = s[pos] - 'a';
if(root -> son[c] == NULL || root -> son[c] -> nwords == 0)
return 0;
return (1 + prefix(s, pos + 1, root -> son[c]));
}
Trie* root;
int main() {
ifstream in("trie.in");
ofstream out("trie.out");
root = new Trie();
int tip;
string s;
while(in >> tip >> s) {
if(tip == 0)
addTrie(s, 0, root);
if(tip == 1)
delTrie(s, 0, root);
if(tip == 2)
out << freq(s, 0, root) << "\n";
if(tip == 3)
out << prefix(s, 0, root) << "\n";
}
return 0;
}