Cod sursa(job #896818)

Utilizator deividFlorentin Dumitru deivid Data 27 februarie 2013 17:28:40
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include<stdio.h>
 
#define maxl 23
#define sigma 26
 
FILE*f=fopen("trie.in","r");
FILE*g=fopen("trie.out","w");
 
char sir[maxl];
 
struct trie{
    int nrc,down;
    trie *son[sigma];
     
    trie () {
        nrc = down = 0;
        for ( int i = 0 ; i < sigma ; ++i ){
            son[i] = NULL;
        }
    }
};
 
trie *R = new trie;
 
void insert ( trie *nod , char *p ){
     
    if ( !((*p) >= 'a' && (*p) <= 'z') ){
        ++nod->nrc; ++nod->down;
        return ;
    }
     
    ++nod->down;
     
    int ch = (*p)-'a';
    if ( nod->son[ch] == NULL ){
        nod->son[ch] = new trie;
    }
    insert(nod->son[ch],p+1);
}
 
void erase ( trie *nod , char *p ){
     
    int ch = (*p)-'a';
    if ( !(ch >= 0 && ch < sigma) ){
        --nod->nrc; --nod->down;
        return ;
    }
     
    erase(nod->son[ch],p+1);
     
    --nod->down;
    if ( !(nod->son[ch]->down) ){
        delete nod->son[ch];
        nod->son[ch] = NULL;
    }
}
 
int search ( trie *nod , char *p ){
     
    int ch = (*p)-'a';
    if ( !(ch >= 0 && ch < sigma) ){
        return nod->nrc;
    }
     
    if ( nod->son[ch] == NULL )  return 0;
    return search(nod->son[ch],p+1);
}
 
int lcs ( trie *nod , char *p ){
     
    int ch = (*p)-'a';
    if ( !(ch >= 0 && ch < sigma) ){
        return 0;
    }
     
    if ( nod->son[ch] == NULL )  return 0;
    return 1+lcs(nod->son[ch],p+1);  
}
 
int main () {
     
    int op;
    while ( fscanf(f,"%d ",&op) == 1 ){
         
        fscanf(f,"%s",sir+1);
        if ( op == 0 ){
            insert(R,sir+1);
        }
        else{
            if ( op == 1 ){
                erase(R,sir+1);
            }
            else{
                if ( op == 2 ){
                    fprintf(g,"%d\n",search(R,sir+1));
                }
                else{
                    fprintf(g,"%d\n",lcs(R,sir+1));
                }
            }
        }
    }
     
    fclose(f);
    fclose(g);
     
    return 0;
}