Cod sursa(job #2446270)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 7 august 2019 16:48:38
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie{
    int apparitions;
    trie *letters[26];
    trie(){
        apparitions = 0;
        for(int i = 0; i <= 25; ++i)
            letters[i] = nullptr;
    }

}*root;
void insertt(string s){
    trie *current = root;
    current -> apparitions += 1;
    for(auto character : s){
        int currentch = character - 'a';
        if(!current -> letters[currentch])
            current -> letters[currentch] = new trie();
        current = current -> letters[currentch];
        current -> apparitions += 1;

    }
}
void erasee(string s){
    trie *current = root;
    current -> apparitions -= 1;
    for(auto character : s){
        int currentch = character - 'a';
        current = current -> letters[currentch];
        current -> apparitions -= 1;
    }
}
int appnumber(string s){
    trie *current = root;
    for(auto character : s){
        int currentch = character - 'a';
        if(current -> letters[currentch] == nullptr)
            return 0;
        current = current -> letters[currentch];
    }
    int sum = 0;
    for(int i = 0 ;i <= 25; ++i){
        if(current -> letters[i] == nullptr) continue;
        sum += current -> letters[i] -> apparitions;
    }
    return current -> apparitions - sum;
}
int longestpre(string s){
    int contor = 0;
    trie *current = root;
    for(auto character : s){
        int currentch = character - 'a';
        if(!current -> letters[currentch] || !current -> letters[currentch] -> apparitions)
            return contor;
        contor++;
        current = current -> letters[currentch];
    }
    return contor;
}
int main(){
    int type;
    root = new trie();
    string s;
    while(fin >> type >> s){
        if(type == 0) insertt(s);
        else if(type == 1) erasee(s);
        else if(type == 2) fout << appnumber(s) << '\n';
        else if(type == 3) fout << longestpre(s) << '\n';
    }
    return 0;
}