Cod sursa(job #2871332)

Utilizator handicapatucavasi eduard handicapatu Data 14 martie 2022 13:15:59
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

struct Node{
    int nrSons , nrWords;
    Node *alpha[26];
    Node(){
        nrSons = nrWords = 0;
        for(int i = 0 ; i < 26 ; ++i)
            alpha[i] = 0;
    }
};

Node *root = new Node;
char s[21];
int type;
int w;

void insertNode(Node *crawl , char *s){
    if(*s == '\0'){
        ++crawl -> nrWords;
        return;
    }
    else{
        if(!crawl -> alpha[*s - 'a'])
            ++crawl -> nrSons , crawl -> alpha[*s - 'a'] = new Node;
        insertNode(crawl -> alpha[*s - 'a'] , s + 1);
    }
}

bool deleteNode(Node *crawl , char *s){
    if(*s == '\0'){
        --crawl -> nrWords;
    }
    else if(deleteNode(crawl -> alpha[*s - 'a'] , s + 1)){
        crawl -> alpha[*s - 'a'] = 0;
        --crawl -> nrSons;
    }
    if(crawl -> nrWords == 0 && crawl -> nrSons == 0 && crawl != root){
        delete crawl;
        return 1;
    }
    return 0;
}

int nrAp(Node *crawl , char *s){
    if(*s == '\0')
        return crawl -> nrWords;
    else if(crawl -> alpha[*s - 'a'])
        return nrAp(crawl -> alpha[*s - 'a'] , s + 1);
    return 0;
}

int prefix(Node *crawl , char *s , int k){
    if(!crawl -> alpha[*s - 'a'] or *s == '\0')
        return k;
    return prefix(crawl -> alpha[*s - 'a'] , s + 1 , k + 1);
}

int main(){
    while(f >> type){
        f >> s;
        if(type == 0)
            insertNode(root , s);
        else if(type == 1)
            deleteNode(root , s);
        else if(type == 2)
            g << nrAp(root , s) << "\n";
        else if(type == 3)
            w = 0 , g << prefix(root , s , w) << "\n";
    }
    return 0;
}