Pagini recente » Cod sursa (job #1876265) | Cod sursa (job #1148515) | Cod sursa (job #1049881) | Cod sursa (job #2953818) | Cod sursa (job #616675)
Cod sursa(job #616675)
#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);
for (int i = 0; i < 26; i++) letter[i] = 0;
words = 0;
childs = 0;
}
~Trie(){
letter.clear();
}
void add(string s) {
Trie *prev, *curent = this;
char a;
for (int i = 0; i < (int)s.length(); i++){
a = s[i];
if (curent->letter[idx] == 0) {
curent->letter[idx] = new Trie;
curent->childs++;
}
prev = curent;
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);
curent->words--;
do{
st.pop();
for (int i = 0; i < 26; i++)
if ( st.top()->letter[i] == curent){
delete curent;
st.top()->letter[i] = 0;
st.top()->childs--;
break;
}
curent = st.top();
}while ( st.top()->words == 0 && st.top()->childs == 0 && !st.empty());
}
int times(string s){
Trie *prev, *curent = this;
char a;
for (int i = 0; i < (int)s.length(); i++){
a = s[i];
prev = curent;
curent = curent->letter[idx];
}
return curent->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;
}
};
#include <iostream>
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){
int a = t->longestPrefix(s);
fout << a << '\n';
}
}while ( fin >> op >> s);
//delete t;
return 0;
}