Pagini recente » Cod sursa (job #554757) | Cod sursa (job #123828) | Cod sursa (job #126837) | Cod sursa (job #123839) | Cod sursa (job #3238302)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int tip;
string sir;
struct TrieNode {
TrieNode* copil[26];
bool finalCuvant;
int nrCuvinte;
TrieNode() {
finalCuvant = false, nrCuvinte = 0;
for(int i=0; i<26; i++) copil[i] = NULL;
}
};
class Trie {
private:
TrieNode* root;
public:
Trie() { root = new TrieNode(); }
void adaugareCuvant(string cuvant) {
TrieNode* nod = root;
for(char ch : cuvant) {
int index = ch - 'a';
if(!nod->copil[index]) nod->copil[index] = new TrieNode();
nod = nod->copil[index];
}
nod->finalCuvant = true, nod->nrCuvinte++;
}
bool eUltimNod(TrieNode* nod) {
for(int i=0; i<26; i++)
if(nod->copil[i]) return false;
return true;
}
TrieNode* stergereCuvant(TrieNode* nod, string cuvant, int adancime = 0) {
if(!nod) return NULL;
if(adancime == cuvant.size()) {
if(nod->finalCuvant) nod->finalCuvant = false, nod->nrCuvinte--;
if(eUltimNod(nod)) {
delete (nod);
nod = NULL;
}
return nod;
}
int index = cuvant[adancime] - 'a';
nod->copil[index] = stergereCuvant(nod->copil[index], cuvant, adancime + 1);
if(eUltimNod(nod) && nod->finalCuvant == false) {
delete (nod);
nod = NULL;
}
return nod;
}
void stergereCuvant(string cuvant) { stergereCuvant(root, cuvant); }
int longestPrefix(string cuvant) {
TrieNode* nod = root;
int cnt = 0;
for(char ch : cuvant) {
int index = ch - 'a';
if(!nod->copil[index]) return cnt;
nod = nod->copil[index], cnt++;
}
return cnt;
}
int gasireCuvinte(string cuvant) {
TrieNode* nod = root;
for(char ch : cuvant) {
int index = ch - 'a';
if(!nod->copil[index]) return 0;
nod = nod->copil[index];
}
return nod->nrCuvinte;
}
};
int main()
{
Trie trie;
while(fin >> tip >> sir) {
if(tip == 0) trie.adaugareCuvant(sir);
else if(tip == 1) trie.stergereCuvant(sir);
else if(tip == 2) fout << trie.gasireCuvinte(sir) << '\n';
else fout << trie.longestPrefix(sir) << '\n';
}
return 0;
}