Pagini recente » Cod sursa (job #652841) | Cod sursa (job #1025086) | Cod sursa (job #780277) | Cod sursa (job #1581542) | Cod sursa (job #616607)
Cod sursa(job #616607)
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#define idx (s[i] - 'a')
using namespace std;
class Trie{
vector<Trie*> letter;
int words;
int childs;
public:
Trie(){
letter.resize(26);
words = 0;
childs = 0;
}
void add(string s) {
Trie *curent = this;
for (int i = 0; i < (int)s.length(); i++){
if (curent->letter[idx] == 0) {
curent->letter[idx] = new Trie;
curent->childs++;
}
curent = curent->letter[idx];
}
curent->words++;
}
void rem(string s) {
stack<Trie*> st;
Trie *curent = this;
char a;
for (int i = 0; i < (int)s.length(); i++){
st.push(curent);
curent = curent->letter[idx];
a = s[i];
}
st.push(curent);
st.top()->words--;
while (st.top()->words == 0 && st.top()->childs == 0){
Trie *aux = st.top();
st.pop();
delete aux;
}
}
int times(string s){
Trie *prev, *curent = this;
for (int i = 0; i < (int)s.length(); i++){
prev = curent;
curent = curent->letter[idx];
}
return prev->words;
}
int longestPrefix(string s) {
Trie *curent = this;
int length = 0;
for (int i = 0; i < (int)s.length() && curent; i++){
if ( curent->letter[idx] != 0 ) length = i + 1;
curent = curent->letter[idx];
}
return length;
}
};
int main(){
string s;
int op;
Trie *t = new Trie();
ifstream fin("trie.in");
ofstream fout("trie.out");
fin >> op >> s;
do {
if (op == 0)
t->add(s);
if (op == 1)
t->rem(s);
if (op == 2){
int a = t->times(s);
fout << a << '\n';
}
if (op == 3)
fout << t->longestPrefix(s) << '\n';
}while ( fin >> op >> s);
//delete t;
return 0;
}