Cod sursa(job #2630736)

Utilizator doyouhavethetimeStanculescu Gabriel doyouhavethetime Data 26 iunie 2020 23:56:11
Problema Trie Scor 5
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct nod {
    int ct;
    int n;
    struct nod* fii[26];
} *T;

void add (struct nod* *p, char *s) {
    if (isspace(*s))
        (*p)->ct++;
    else {
        if (!((*p)->fii[*s-'a'])) {
            (*p)->fii[*s-'a']=(struct nod*)calloc(1, sizeof (struct nod));
            (*p)->n++;
        }
        add(&(*p)->fii[*s-'a'], s+1);
    }
}

char del (struct nod* *p, char *s) {
    if (isspace(*s))
        (*p)->ct++;
    else
        if (del(&(*p)->fii[*s-'a'], s+1)) {
            (*p)->fii[*s-'a']=0;
            (*p)->n--;
        }

    if (!(*p)->ct && !(*p)->n && (*p)!=T) {
        free(*p);
        return 1;
    }
    return 0;
}

int query (struct nod *p, char *s) {
    if (isspace(*s))
        return p->ct;
    if (p->fii[*s-'a'])
        return query(p->fii[*s-'a'], s+1);
    return 0;
}

int prefix (struct nod *p, char *s, int k) {
    if (isspace(*s) || !p->fii[*s-'a'])
        return k;
    return prefix(p->fii[*s-'a'], s+1, k+1);
}

int main (void) {
    FILE *fin=fopen("trie.in", "r"),
         *fout=fopen("trie.out", "w");
    T=(struct nod*)calloc(1, sizeof(struct nod));

    char s[23];
    fgets(s, sizeof s, fin);
    while (!feof(fin)) {
        switch (s[0]) {
        case '0':
            add(&T, s+2);
            break;
        case '1':
            del(&T, s+2);
            break;
        case '2':
            fprintf(fout, "%d\n", query(T, s+2));
            break;
        case '3':
            fprintf(fout, "%d\n", prefix(T, s+2, 0));
            break;
        }
        fgets(s, sizeof s, fin);
    }
    return 0;
}