Cod sursa(job #614353)

Utilizator theodora_maneaManea Theodora Maria theodora_manea Data 6 octombrie 2011 10:28:54
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <string.h>
#include <stdlib.h>

#define ch (*s-'a')

using namespace std;

int i,n,m;
typedef struct trie {
    trie *f[26];
    int cnt, nr;
    trie () {
    cnt=nr=0;
    memset(f,0,sizeof(f));
    }
};
trie *T=new trie;
char q[30];

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

void inserare(trie *nod,char *s) {
    if (*s<'a' || *s>'z') {
       nod->cnt++;
       return;
    }
    if (nod->f[ch]==0) {
       nod->f[ch]=new trie;
       nod->nr++;
    }
    inserare(nod->f[ch],s+1);
}

int sterge(trie *nod,char *s) {
    if (*s<'a' || *s>'z') nod->cnt--;
    else
        if (sterge(nod->f[ch],s+1)) {
            nod->f[ch]=0;
            nod->nr--;
        }
        if (nod->cnt==0 && nod->nr==0 && nod!=T) {
            delete nod;
            return 1;
        }
        return 0;
}

int aparitie(trie *nod, char *s) {
    if (*s<'a' || *s>'z')
        return nod->cnt;
    if (nod->f[ch])
        return aparitie(nod->f[ch],s+1);
    return 0;
}

int prefix(trie *nod, char *s, int k) {
    if ((*s<'a' || *s>'z') || nod->f[ch]==0)
        return k;
    else
        return prefix(nod->f[ch],s+1,k+1);
}

int main () {
    int i=0;
    char ch1;
    while (1) {
         in.getline(q,30);
         i++;
         if (q[0]!=0) {
         if (q[0]=='0') inserare(T,q+2);
         else
         if (q[0]=='1') sterge(T,q+2);
         else
         if (q[0]=='2') out << aparitie(T,q+2) << '\n';
         else
         out << prefix(T,q+2,0) << '\n';
         }
         else break;
    }
    return 0;
}