Cod sursa(job #1613668)

Utilizator razvandRazvan Dumitru razvand Data 25 februarie 2016 16:03:43
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <iostream>
#include <stdio.h>
#include <cstring>
#define MAX 32
#define C *c - 'a'

using namespace std;

char l[MAX];
char *x = l;
FILE *fin;
FILE *fout;

struct trie {
    int am;
    int dim;
    int cnt;
    trie *m[26];
    trie() {
        am = dim = cnt = 0;
        cnt = 1;
        memset(m, 0, sizeof(m));
    }
};
void ins(trie *root, char *c) {
    int a = *c-'a';
    if(root->m[a] == 0) {
        root->m[a] = new trie();
        if(*(c+1) == '\0') {
            root->m[a]->am++;
            return;
        }
        ins(root->m[a], c+1);
        return;
    }
    root->m[a]->cnt++;
    if(*(c+1) == '\0') {
        root->m[a]->am++;
        return;
    }
    ins(root->m[a], c+1);
}

void del(trie *root, char *c) {
    int a = *c-'a';
    if(root->m[a]->cnt == 1) {
        root->m[a] = 0;
        /*root->m[a]->cnt = 0;
        root->m[a]->am = 0;
        root->m[a]->dim = 0;
        memset(root->m[a]->m, 0, sizeof(root->m[a]->m));
        delete root->m[a];*/
        return;
    }
    root->m[a]->cnt--;
    if(*(c+1) == '\0') {
        root->m[a]->am--;
        return;
    }
    del(root->m[a], c+1);
}

int ap(trie *root, char *c) {

    int a = *c-'a';

    if(root->m[a] == 0)
        return 0;

    if(*(c+1) == '\0') {
        return root->m[a]->am;
    } else {
        return ap(root->m[a], c+1);
    }

}

int pref(trie *root, char *c, int crr) {
    char a = *c-'a';
    if(root->m[a] == 0 || root->m[a]->cnt == 0) {
        return crr;
    }
    return pref(root->m[a], c+1, crr+1);
}

trie *r;

int main() {

    fin = fopen("trie.in", "r");
    fout = fopen("trie.out", "w");
    int t;
    char *wa;
    r = new trie();

    fgets(x, MAX, fin);

    while(!feof(fin)) {
        if(x[0] == '0') {
            ins(r, x+2);
        } else if(x[0] == '1') {
            del(r, x+2);
        } else if(x[0] == '2') {
            fprintf(fout, "%d\n", ap(r, x+2));
        } else if(x[0] == '3') {
            fprintf(fout, "%d\n", pref(r, x+2, 0));
        }
        x=l;
        fgets(x, MAX, fin);
    }

    return 0;
}