Pagini recente » Cod sursa (job #2272974) | Cod sursa (job #3178761)
#include <fstream>
#include <string>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
class node{
private:
int cnt, words;
node *v[26];
public:
node(){
cnt = 0;
words = 0;
for(auto &it:v)
it = nullptr;
}
void add(const string &s, const int &poz){
if(poz == s.size()){
cnt++;
words++;
return;
}
if(v[s[poz] - 'a'] == nullptr)
v[s[poz] - 'a'] = new node;
v[s[poz] - 'a']->add(s, poz + 1);
words++;
}
void del(const string &s, const int &poz){
if(poz == s.size()){
cnt--;
words--;
return;
}
v[s[poz] - 'a']->del(s, poz + 1);
words--;
}
int nr_app(const string &s, const int &poz){
if(poz == s.size()){
return cnt;
}
if(v[s[poz] - 'a'] == nullptr)
return 0;
return v[s[poz] - 'a']->nr_app(s, poz + 1);
}
int prefix(const string &s, const int &poz){//cel mai lung prefix al lui s comun cu orice alt cuvant
if(poz == s.size()) {
return poz;
}
if(v[s[poz] - 'a'] == nullptr) {
return poz;
}
if(words == 0)
return poz - 1;
return v[s[poz] - 'a']->prefix(s, poz + 1);
}
};
node *trie = new node;
int main() {
char c;
string s;
while(cin >> c >> s){
if(c == '0')
trie->add(s, 0);
else if(c == '1')
trie->del(s, 0);
else if(c == '2')
cout << trie->nr_app(s, 0) << '\n';
else cout << trie->prefix(s, 0) << '\n';
}
return 0;
}