Cod sursa(job #3173514)

Utilizator richardbaczur1Baczur Richard richardbaczur1 Data 22 noiembrie 2023 23:19:14
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.1 kb
/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <iostream>
#include <cstring>

using namespace std;

struct node {
    int ap, fii;
    node* p[27];
    
    node() {
        memset(p, 0, sizeof(p));
    }
};
node* root;

void solve_zero(node* trie, char* x) {
    if (*x == '\0')  {
        ++trie->ap;
        return;
    }
    else if (trie->p[*x - 'a'] == 0) {
        trie->p[*x - 'a'] = new node();
        ++trie->fii;
    }
    solve_zero(trie->p[*x - 'a'], x + 1);
}

int solve_one(node* trie, char* x) {
    if (*x == '\0') {
        --trie->ap;
    } else if (solve_one(trie->p[*x - 'a'], x + 1)) {
        trie->fii--;
        trie->p[*x - 'a'] = 0;
    }
    
    if (trie->ap == 0 && trie->fii == 0 && trie != root) return 1;
    return 0;
}

void solve_two(node* trie, char* x) {
    if (*x == '\0') {
        printf("%d\n", trie->ap);
        return;
    }
    else solve_two(trie->p[*x - 'a'], x + 1);
}

void solve_three(node* trie, char* x, int sol) {
    if (trie->p[*x - 'a'] == 0) 
    {
        printf("%d\n", sol);
    }
    else 
    {
        solve_three(trie->p[*x - 'a'], x + 1, sol + 1);
    }
}

char* x;
int c;
int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    
    x = (char*) calloc(25, sizeof(char));
    root = new node();
    while (cin >> c >> x) {
        switch (c) {
            case 0:
                solve_zero(root, x);
                break;
            case 1:
                solve_one(root, x);
                break;
            case 2:
                solve_two(root, x);
                break;
            case 3:
                solve_three(root, x, 0);
                break;
        }
    }
    
    fclose(stdin);
    fclose(stdout);

    return 0;
}