Mai intai trebuie sa te autentifici.

Cod sursa(job #1160523)

Utilizator gigel123Ionut. gigel123 Data 30 martie 2014 16:41:43
Problema Trie Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
#include <iostream>
#include <cstring>
#include<fstream>
#include<cstdio>

using namespace std;

class nod{
    int c,nrf;
    nod *f[26];
public:
    nod(){
        c=nrf=0;
        memset(f,0,sizeof(f));
    }
    friend class trie;
};

class trie{
    nod *r;

    void inserare(nod *x,char *s){
        if(s[0]=='\0'){
               x->c++;
               return;
        }
        else{
            if(x->f[s[0]-'a']==0){
                x->nrf++;
                x->f[s[0]-'a']=new nod;
            }
        }
        inserare(x->f[s[0]-'a'],(s+1));


    }

    int sterge(nod *x,char *s){
        if(s[0]=='\0'){
            x->c--;
        }
        else if(sterge(x->f[s[0]-'a'],(s+1))){
                x->nrf--;
                x->f[s[0]-'a']=0;
            }
        if(x->c==0 && x->nrf==0 && x!=r){
            delete x;
            return 1;
        }
        return 0;
    }

    int aparitie(nod *x, char *s){
        if(s[0]=='\0'){
            return x->c;
        }
        if(x->f[s[0]-'a'])return aparitie(x->f[s[0]-'a'],(s+1));
        return 0;
    }

    int prefix(nod *x, char *s, int k){
        if(s[0]=='\0' || x->f[s[0]-'a']==0) return k;
        return prefix(x->f[s[0]-'a'], s+1, k+1);
    }

    bool find(nod*x,char *s){
        if(s[0]=='\0'){
            return 1;
        }
        else {
            if(x->f[s[0]-'a']==0){
                return 0;
            }
            else find(x->f[s[0]-'a'],(s+1));
        }
    }

public:
    trie(){
        r=new nod;
    }
    void start_ins(char *sir){
         inserare(r,sir);
    }
    bool start_find(char *sir){
        return find(r,sir);
    }

    int start_sterge(char *sir){
        return sterge(r,sir);
    }
    int start_ap(char *sir){
        return aparitie(r,sir);
    }
    int start_prefix(char *sir,int k){
        return prefix(r,sir,k);
    }

};



int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    trie d;
    char *s;
    int opt;
    s=new char[32];
    memset(s,0,sizeof(s));

    if(!f.eof()){
        do{
            f>>opt;
            f>>s;
            if(opt==0)d.start_ins(s);
            else if(opt==1)d.start_sterge(s);
            else if(opt==2)g<<d.start_ap(s)<<endl;
            else g<<d.start_prefix(s,0)<<endl;
        }while(!f.eof());
    }



    delete []s;
}