Cod sursa(job #1161612)

Utilizator j.loves_rockJessica Joanne Patrascu j.loves_rock Data 31 martie 2014 12:38:27
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <cstdio>
using namespace std;

struct cuvant {
    int nr;
    cuvant *p[30];
    cuvant() {
        nr=0;
        for (int i=0;i<=29;i++) p[i] = NULL;
    }
};

cuvant r;
char crt[30];
int tip;

void update(int tip) {
    int pct = 0;
    if (r.p[crt[pct]-'a'] == NULL) r.p[crt[pct]-'a'] = new cuvant();
    cuvant *x = r.p[crt[pct]-'a'];
    x->nr+=tip;
    for (pct=1;crt[pct] != 0;pct++) {
        if (x->p[crt[pct]-'a'] == NULL) x->p[crt[pct]-'a'] = new cuvant();
        x = x->p[crt[pct]-'a'];
        x->nr+=tip;
    }
}

int queryA() {
    int pct = 0;
    if (r.p[crt[pct]-'a'] == NULL) return 0;
    cuvant *x = r.p[crt[pct]-'a'];
    for (pct=1;crt[pct] != 0;pct++) {
        if (x->p[crt[pct]-'a'] == NULL) return 0;
        x = x->p[crt[pct]-'a'];
    }
    int nrmin = 0;
    for (int i=0;i<=29;i++) if (x->p[i] != NULL) nrmin += x->p[i]->nr;
    return x->nr - nrmin;
}

int queryB() {
    int dif = queryA();
    int pct = 0;
    if (r.p[crt[pct]-'a'] == NULL) return 0;
    int maxlen = 1;
    cuvant *x = r.p[crt[pct]-'a'];
    if (x->nr == 0) return 0;
    for (pct=1;crt[pct] != 0;pct++) {
        if (x->p[crt[pct]-'a'] == NULL || x->p[crt[pct]-'a']->nr == 0) {
            return maxlen;
        } else {
            x = x->p[crt[pct]-'a'];
            maxlen++;
        }
    }
    return maxlen;
}

int main() {
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    scanf("%d %s",&tip,crt);
    while (!feof(stdin)) {

        if (tip == 0) {
            update(1);
        } else if (tip == 1) {
            update(-1);
        } else if (tip == 2) {
            printf("%d\n",queryA());
        } else if (tip == 3) {
            printf("%d\n",queryB());
        }
        scanf("%d %s",&tip,crt);
    }
    return 0;
}