Cod sursa(job #3228943)

Utilizator andreea678Rusu Andreea-Cristina andreea678 Data 12 mai 2024 15:04:29
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct node{
    int sonct;
    int ct;
    node* son[26];
    node(){
        ct=sonct=0;
        for (int i=0; i<26; ++i){
            son[i]=0;
        }
    }
};
node* root=new node;
void add(node* nod, char cuvant[23]){
    int i=0;
    while(i<strlen(cuvant)){
        int c=cuvant[i]-'a';
        if (nod->son[c] == NULL){
            nod->son[c]=new node;
        }
        nod=nod->son[c];
        nod->ct++;
        i++;
    }
    nod->sonct++;
}
void del(node* nod, char cuvant[23]){
    int i=0;
    while (i<strlen(cuvant)){
        int c=cuvant[i]-'a';
        nod=nod->son[c];
        nod->ct--;
        i++;
    }
    nod->sonct--;
}
int occur(node *nod, char cuvant[23]){
    int i=0;
    while (i<strlen(cuvant)){
        int c=cuvant[i]-'a';
        if (nod->son[c] == NULL || nod->son[c]->ct == 0){
            return 0;
        }
        nod=nod->son[c];
        i++;
    }
    return nod->sonct;
}
int prefix(node *nod, char cuvant[23]){
    int i=0;
    int maxim=-1;
    while (i<strlen(cuvant)){
        int c=cuvant[i]-'a';
        if (nod->son[c] == NULL || nod->son[c]->ct==0){
            return i;
        }
        nod=nod->son[c];
        i++;
    }
    return i;
}
int main()
{
    int op;
    char cuvant[23];
    while (fin >> op >> cuvant){
        if (op==0){
            add(root, cuvant);
        }
        if (op==1){
            del(root, cuvant);
        }
        if (op==2){
            fout << occur(root, cuvant) << '\n';
        }
        if (op==3){
            fout << prefix(root, cuvant) << '\n';
        }
    }
    return 0;
}