Cod sursa(job #2269570)

Utilizator Dobricean_IoanDobricean Ionut Dobricean_Ioan Data 26 octombrie 2018 10:39:11
Problema Trie Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <iostream>
#include <fstream>
 
const int SIGMA = 27;
 
using namespace std;
 
ifstream in("trie.in");
ofstream out("trie.out");
 
struct Trie{
    int frequency;
    Trie *child[SIGMA];
 
    Trie(){
        this->frequency = 0;
        for(int i = 0; i < SIGMA; i++)
            child[i] = nullptr;
    }
};
 
void trie_insert(string s, Trie *& nod){
    Trie *curent = nod;
    for(auto x : s){
        if(curent -> child[x - 'a'] == nullptr)
            curent -> child[x - 'a'] = new Trie();
        curent = curent -> child[x - 'a'];
        curent->frequency++;
    }
}
void trie_delete(string s, Trie *& nod){
    Trie *curent = nod;
    for(auto x : s){
        curent = curent -> child[x - 'a'];
        curent -> frequency--;
    }
}
int trie_frequency(string s, Trie *& nod){
    Trie *curent = nod;
    for(auto x : s){
        if(curent -> child[x - 'a'] == nullptr)
            return 0;
        curent = curent -> child[x - 'a'];
    }
    int addition = 0;
    for(int i = 0; i < SIGMA; i++){
        if(curent->child[i] != nullptr)
            addition += curent->child[i]->frequency;
    }
    return curent->frequency - addition;
}
int trie_longest_prefix(string s, Trie *& nod){
    Trie *curent = nod;
    int ans = 0;
    for(auto x : s){
        if(curent -> child[x - 'a'] == nullptr || !curent -> child[x - 'a'] -> frequency)
            return ans;
        curent = curent -> child[x - 'a'];
        ans++;
    }
    return ans;
}
 
int main()
{
    Trie *root;
    root = new Trie();
 
    char type;
    string s;
    while(in>>type>>s){
        type -= '0';//#professional
        if(type == 0)
            trie_insert(s,root);
        else if(type == 1)
            trie_delete(s,root);
        else if(type == 2)
            out<<trie_frequency(s,root)<<"\n";
        else if(type == 3)
            out<<trie_longest_prefix(s,root)<<"\n";
    }
    return 0;
}