Pagini recente » Cod sursa (job #2082625) | Cod sursa (job #2924836) | Cod sursa (job #2066310) | Cod sursa (job #495071) | Cod sursa (job #766483)
Cod sursa(job #766483)
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <fstream>
#define trie node*
using namespace std;
typedef struct node{
int nrCuv;
trie nextT[26];
int nrPr;
} node;
trie T;
trie createT() {
trie tr = new node();
tr->nrCuv = 0;
tr->nrPr = 0;
memset(tr->nextT, 0, 26 * sizeof(trie));
return tr;
}
void add_(string word) {
trie R = T;
int i = 0;
while (i < word.length()) {
int poz = word[i] - 'a';
if (T->nextT[poz] == NULL) {
T->nextT[poz] = createT();
}
T = T->nextT[poz];
if (i == word.length() - 1) {
T->nrCuv++;
}
T->nrPr++;
i++;
}
T = R;
}
void del_(string word) {
trie R = T;
int i = 0;
while (i < word.length()) {
int poz = word[i] - 'a';
T = T->nextT[poz];
if (i == word.length() - 1) {
T->nrCuv--;
}
T->nrPr--;
i++;
}
T = R;
}
void print_nrCuv(string word) {
trie R = T;
int i = 0;
while (i < word.length() && T->nextT[word[i] - 'a'] != NULL) {
int poz = word[i] - 'a';
T = T->nextT[poz];
i++;
}
printf("%d\n", T->nrCuv);
T = R;
}
void print_pref(string word) {
trie R = T;
int i = 0;
int lmax = 0;
while (i < word.length() && T->nextT[word[i] - 'a'] != NULL) {
int poz = word[i] - 'a';
T = T->nextT[poz];
i++;
if (T->nrPr > 0) {
lmax = i;
}
}
printf("%d\n", lmax);
T = R;
}
// Functie suplimentara pentru afisarea trie-ului
void print_trie(trie tr, int poz, char c) {
for (int i = 0; i <= poz; i++) {printf(" ");}
printf("%d %c\n", tr->nrCuv, c);
for (int i = 0; i <= 25; i++) {
if (tr->nextT[i] != NULL) {
print_trie(tr->nextT[i], poz + 1, i + 'a');
}
}
}
// Functie suplimentara pentru afisarea trie-ului
void print_tr(string word) {
cout<< "word: " << word << endl;
printf("trie:\n");
print_trie(T, 0, '#');
}
void read_() {
ifstream in("trie.in");
while (!in.eof()) {
string word;
int op;
in >> op >> word;
switch (op) {
case 0:
add_(word);
//printf("\nadd:\n");print_tr(word);
break;
case 1:
del_(word);
//printf("\ndell:\n");print_tr(word);
break;
case 2:
print_nrCuv(word);
break;
case 3:
print_pref(word);
break;
default:
break;
}
}
}
void init_() {
T = createT();
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
init_();
read_();
return 0;
}