Pagini recente » Cod sursa (job #2682920) | Cod sursa (job #1640303) | Cod sursa (job #1536979) | Cod sursa (job #2449044) | Cod sursa (job #2006358)
#include <iostream>
#include <fstream>
#include <string>
#include <assert.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
#define c (w[pos] - 'a')
#define r (root -> children[w[0] - 'a'])
struct Node {
int words = 0;
int prefixes = 0;
Node* children[27];
Node() {
words = prefixes = 0;
for (int i = 0; i < 27; ++i) children[i] = 0;
}
};
Node* root = new Node();
void addWord(Node* v, string& w, int pos = 0) {
v -> prefixes++;
if (pos == w.size() - 1) {
v -> words++;
return;
}
pos++;
if (v -> children[c] == 0) v -> children[c] = new Node();
addWord(v -> children[c], w, pos);
}
int countWords(Node* v, string& w, int pos = 0) {
if (pos == w.size() - 1) return v -> words;
pos++;
if (v -> children[c] == 0) return 0;
return countWords(v -> children[c], w, pos);
}
void deleteWord(Node* v, string& w, int pos = 0) {
if (pos == w.size() - 1) {
v -> words--;
v -> prefixes--;
} else {
v -> prefixes--;
pos++;
deleteWord(v -> children[c], w, pos);
}
if (v -> prefixes == 0) {
v = nullptr;
delete v;
}
}
int longestPrefix(Node* v, string &w) {
int k = 0;
int pos = 0;
while (v && v -> prefixes > 0) {
k++;
if (++pos >= w.size()) break;
v = v -> children[c];
}
return k;
}
int main()
{
for (int i = 0; i < 27; ++i) root -> children[i] = new Node();
int o;
string w;
while (!in.eof()) {
in >> o >> w;
switch(o) {
case 0: addWord(r, w); break;
case 1: deleteWord(r, w); break;
case 2: out << countWords(r, w) << '\n'; break;
case 3: out << longestPrefix(r, w) << '\n'; break;
}
}
return 0;
}