Pagini recente » Cod sursa (job #958302) | Cod sursa (job #261779) | Cod sursa (job #2169404) | Cod sursa (job #2466568) | Cod sursa (job #2870143)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node {
int cnt, sonCount;
Node* sons[26];
Node() {
cnt = 0;
sonCount = 0;
memset(sons, 0, sizeof(sons));
}
};
Node* root = new Node;
void adaugaCuvant(char* s, Node *node) {
char c = *s;
if (c == '\0') {
node -> cnt++;
return;
}
int i = c - 'a';
if (node -> sons[i] == NULL) {
node -> sons[i] = new Node;
node -> sonCount++;
}
adaugaCuvant(s + 1, node -> sons[i]);
}
bool deleteCuvant(char* s, Node *node) {
char c = *s;
if (c == '\0') {
node -> cnt--;
}
else {
int i = c - 'a';
if (deleteCuvant(s + 1, node -> sons[i])) {
node -> sonCount--;
node -> sons[i] = NULL;
}
}
if (node != root && node -> cnt == 0 && node -> sonCount == 0) {
delete node;
return true;
}
return false;
}
int getAparitii(char *s, Node *node) {
char c = *s;
if (c == '\0') {
if (strlen(s) == 0) {
return node -> cnt;
}
return 0;
}
int i = c - 'a';
if (node -> sons[i] == NULL) {
return 0;
}
return getAparitii(s + 1, node -> sons[i]);
}
int getLongestPrefix(char *s, Node *node) {
char c = *s;
if (node -> cnt == 0 && node -> sonCount == 0) {
return 0;
}
if (c == '\0') {
return 0;
}
int i = c - 'a';
if (node -> sons[i] == NULL) {
return 0;
}
return getLongestPrefix(s + 1, node -> sons[i]) + 1;
}
int main()
{
int k;
char w[21];
while (fin >> k >> w) {
if (k == 0) {
adaugaCuvant(w, root);
}
else if (k == 1) {
deleteCuvant(w, root);
}
else if (k == 2) {
fout << getAparitii(w, root) << "\n";
}
else {
fout << getLongestPrefix(w, root) << "\n";
}
}
return 0;
}