Cod sursa(job #1613655)

Utilizator razvandRazvan Dumitru razvand Data 25 februarie 2016 15:52:06
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.85 kb
#include <iostream>
#include <stdio.h>
#include <cstring>
#define MAX 8000
#define C *c - 'a'

using namespace std;

char buf[MAX];
int ch = MAX;
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));
    }
};

char nextch() {
    if(ch == MAX) {
        fread(buf, 1, MAX, fin);
        ch = 0;
    }
    return buf[ch++];
}

int nextint() {
    int rez = 0;
    char c = nextch();
    while(c == ' ')
        c = nextch();
    int cnt = 0;
    bool f = false;
    while(c >= '0' && c <= '9') {
        rez += c - '0';
        f = true;
        c = nextch();
    }
    if(!f)
        return -1;
    return rez;
}
char w[32];
char* word() {
    char *p = w;
    char c = nextch();
    while(c == ' ')
        c = nextch();
    int cnt = 0;
    while(c >= 'a' && c <= 'z') {
        *p++ = c;
        c = nextch();
    }
    *p++ = '\0';
    p=w;
    return p;
}

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();

    while(true) {

        t = nextint();
        if(t == -1)
            break;
        wa = word();

        if(t == 0) {
            ins(r, wa);
        } else if(t == 1) {
            del(r, wa);
        } else if(t == 2) {
            fprintf(fout, "%d\n", ap(r, wa));
        } else if(t == 3) {
            fprintf(fout, "%d\n", pref(r, wa, 0));
        }

    }
    cout << r->m['l'-'a']->m['a'-'a']->am;

    return 0;
}