Pagini recente » Cod sursa (job #1911159) | Cod sursa (job #1048197) | Cod sursa (job #2412470) | Cod sursa (job #1365131) | Cod sursa (job #1814669)
#include<fstream>
#include<vector>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct node {
node* nextNode[30] = {};
long long cuvinteSf = 0;
long long cuvinteContin = 0;
};
node* root = new node;
/*
adauga un cuvant in arbore
*/
void add(node* currentNode, char* character) {
currentNode->cuvinteContin++; //cate cuvinte trec prin nodul acesta
if (character[0] == '\0') { //sfarsitul unui cuvant
currentNode->cuvinteSf++;
return;
}
int pos = character[0] - 'a';//the next letter
if (currentNode->nextNode[pos] == nullptr) {
currentNode->nextNode[pos] = new node;
}
add(currentNode->nextNode[pos], character + 1);
}
/*
sterge un cuvant din arbore
*/
bool remove(node* currentNode, char* character) {
currentNode->cuvinteContin--;
if (character[0] == '\0') {
currentNode->cuvinteSf--;
}
else {
int pos = character[0] - 'a';
if (remove(currentNode->nextNode[pos], character + 1)) {
currentNode->nextNode[pos] = nullptr;
}
}
if (currentNode->cuvinteContin == 0 && currentNode != root) {
delete currentNode;
return true; //am sters un nod in iteratie
}
return false; //nu am sters niciun nod in iteratie
}
/*
tipareste numarul de aparitii ale cuvantului w in lista
*/
int tipareste(node* currentNode, char* character) {
if (character[0] == '\0') {
return currentNode->cuvinteSf;
}
int pos = character[0] - 'a';
if (currentNode->nextNode[pos] == nullptr) {
return 0;
}
tipareste(currentNode->nextNode[pos], character + 1);
}
/*
lungimea celui mai lung prefix comun
*/
int prefix(node* currentNode, char* character, int lung) {
if (character[0] == '\0') {
return lung; //daca am parcurs cuvantul pana la sfarsit
}
int pos = character[0] - 'a';
if (currentNode->nextNode[pos] == nullptr) {
return lung; //returnam prima pozitie pentru care nu avem succesori
}
if (currentNode->nextNode[pos] != nullptr) {
prefix(currentNode->nextNode[pos], character + 1, lung + 1);
}
}
int main() {
char word[30];
int op;
while (fin >> op) {
fin >> word;
if (op == 0) {
add(root, word);
}
else if (op == 1) {
remove(root, word);
}
else if (op == 2) {
fout << tipareste(root, word) << "\n";
}
else {
fout << prefix(root, word, 0) << "\n";
}
}
}