Pagini recente » Cod sursa (job #1174692) | Cod sursa (job #1269350) | Cod sursa (job #2228683) | Cod sursa (job #1645466) | Cod sursa (job #903343)
Cod sursa(job #903343)
#include <cstdio>
#include <cstring>
#include <cassert>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <map>
using namespace std;
typedef long long LL;
typedef vector<int>::iterator it;
const int oo = 0x3f3f3f3f;
struct Node {
int Size, Frequence;
map<char, Node*> Sons;
Node() {
Size = Frequence = 0;
}
};
Node *T;
void Insert(Node *X, string &Word, int Index) {
++X->Size;
if (Index >= static_cast<int>(Word.size())) {
++X->Frequence;
return;
}
if (X->Sons.find(Word[Index]) == X->Sons.end())
X->Sons[Word[Index]] = new Node;
Insert(X->Sons[Word[Index]], Word, Index + 1);
}
void Erase(Node *X, string &Word, int Index) {
--X->Size;
if (Index >= static_cast<int>(Word.size())) {
--X->Frequence;
return;
}
Erase(X->Sons[Word[Index]], Word, Index + 1);
if (X->Sons[Word[Index]]->Size == 0) {
delete X->Sons[Word[Index]];
X->Sons.erase(Word[Index]);
}
}
int QueryFrequence(Node *X, string &Word, int Index) {
if (Index >= static_cast<int>(Word.size()))
return X->Frequence;
if (X->Sons.find(Word[Index]) == X->Sons.end())
return 0;
return QueryFrequence(X->Sons[Word[Index]], Word, Index + 1);
}
int QueryLCP(Node *X, string &Word, int Index) {
if (Index >= static_cast<int>(Word.size()))
return Index;
if (X->Sons.find(Word[Index]) == X->Sons.end())
return Index;
return QueryLCP(X->Sons[Word[Index]], Word, Index + 1);
}
int main() {
T = new Node;
ifstream in("trie.in");
ofstream out("trie.out");
int Type; string Word;
while ((in >> Type >> Word)) {
if (Type == 0)
Insert(T, Word, 0);
if (Type == 1)
Erase(T, Word, 0);
if (Type == 2)
out << QueryFrequence(T, Word, 0) << "\n";
if (Type == 3)
out << QueryLCP(T, Word, 0) << "\n";
}
in.close();
out.close();
return 0;
}