Cod sursa(job #3173519)

Utilizator richardbaczur1Baczur Richard richardbaczur1 Data 22 noiembrie 2023 23:26:04
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 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 <fstream>
#include <cstring>

using namespace std;

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

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') {
        g << trie->ap << "\n";
        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) 
    {
        g << sol << "\n";
    }
    else 
    {
        solve_three(trie->p[*x - 'a'], x + 1, sol + 1);
    }
}

char* x;
int c;
int main()
{
    x = (char*) calloc(32, sizeof(char));
    root = new node();
    while (f.getline(x, 32) && x[0] != EOF) {
        switch (x[0]) {
            case '0':
                solve_zero(root, x + 2);
                break;
            case '1':
                solve_one(root, x + 2);
                break;
            case '2':
                solve_two(root, x + 2);
                break;
            case '3':
                solve_three(root, x + 2, 0);
                break;
        }
    }
    return 0;
}