Cod sursa(job #2175624)

Utilizator circeanubogdanCirceanu Bogdan circeanubogdan Data 16 martie 2018 18:09:56
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>

using namespace std;

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

int n, tip;

char sir[21];

struct node{
    int ap, ok;
    node *v[27];
    node(){
        for(int i = 0; i < 27; ++ i)
            v[i] = NULL;
        ap = 0;
    }
};

node *root;

void add(node *nod, char *sir){
    if(*sir == 0){
        ++ nod->ap;
        return;
    }
    if(nod->v[*sir - 'a'] == NULL){
        nod->v[*sir - 'a'] = new node;
        ++ nod->ok;
    }
    add(nod->v[*sir - 'a'], sir + 1);
}

void del(node *&nod, char *sir){
    if(*sir == 0){
        -- nod->ap;
        if(nod->ap == 0 && nod->ok == 0 && nod != root){
            delete nod;
            nod = NULL;
        }
        return;
    }
    del(nod->v[*sir - 'a'], sir + 1);
    if(nod->v[*sir - 'a'] == NULL){
        -- nod->ok;
        if(nod->ap == 0 && nod->ok == 0 && nod != root){
            delete nod;
            nod = NULL;
        }
    }
}

int count(node *nod, char *sir){
    if(*sir == 0){
        return nod->ap;
    }
    if(nod->v[*sir - 'a'] == NULL)
        return 0;
    return count(nod->v[*sir - 'a'], sir + 1);
}

int max_seq(node *nod, char *sir){
    if(*sir == 0)
        return 0;
    if(nod->v[*sir - 'a'] == NULL)
        return 0;
    return 1 + max_seq(nod->v[*sir - 'a'], sir + 1);
}

int main(int argc, const char * argv[]) {
    root = new node;
    while(in>>tip>>sir){
        switch(tip){
            case 0: add(root, sir); break;
            case 1: del(root, sir); break;
            case 2: out<<count(root, sir)<<"\n"; break;
            case 3: out<<max_seq(root, sir)<<"\n"; break;
        }
        for(int i = 0; i < 21; ++ i)
            sir[i] = NULL;
    }
    return 0;
}