Pagini recente » Cod sursa (job #2943596) | Cod sursa (job #1011089) | Cod sursa (job #623191) | Cod sursa (job #2062759) | Cod sursa (job #2763918)
#include <fstream>
#include <vector>
#include <string>
struct nod {
std::vector <std::pair <char, int>> children;
int cnt = 0;
int uses = 0;
};
std::vector <nod> trie;
void add(std::string str) {
int pos, node;
bool moved;
pos = 0;
node = 0;
while (pos < (int)str.size()) {
trie[node].uses++;
moved = false;
for (int index = 0; index < (int)trie[node].children.size(); index++) {
if (trie[node].children[index].first == str[pos]) {
pos++;
node = trie[node].children[index].second;
moved = true;
break;
}
}
if (!moved) {
break;
}
}
while (pos < (int)str.size()) {
trie[node].uses++;
trie[node].children.push_back({ str[pos], (int)trie.size() });
trie.push_back({});
node = (int)trie.size() - 1;
pos++;
}
trie[node].cnt++;
trie[node].uses++;
}
void del(std::string str) {
int pos, node;
pos = 0;
node = 0;
while (pos < (int)str.size()) {
trie[node].uses--;
for (int index = 0; index < (int)trie[node].children.size(); index++) {
if (trie[node].children[index].first == str[pos]) {
pos++;
node = trie[node].children[index].second;
break;
}
}
}
trie[node].cnt--;
trie[node].uses--;
}
int count(std::string str) {
int pos, node;
bool moved;
pos = 0;
node = 0;
while (pos < (int)str.size()) {
moved = false;
for (int index = 0; index < (int)trie[node].children.size(); index++) {
if (trie[node].children[index].first == str[pos]) {
pos++;
node = trie[node].children[index].second;
moved = true;
break;
}
}
if (!moved) {
return 0;
}
}
return trie[node].cnt;
}
int pref(std::string str) {
int pos, node;
bool moved;
pos = 0;
node = 0;
while (pos < (int)str.size()) {
moved = false;
for (int index = 0; index < (int)trie[node].children.size(); index++) {
if (trie[node].children[index].first == str[pos] &&
trie[trie[node].children[index].second].uses) {
pos++;
node = trie[node].children[index].second;
moved = true;
}
}
if (!moved) {
break;
}
}
return pos;
}
int main()
{
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
int task;
std::string stri;
trie.push_back({});
while (fin >> task) {
fin >> stri;
if (task == 0) {
add(stri);
}
if (task == 1) {
del(stri);
}
if (task == 2) {
fout << count(stri) << '\n';
}
if (task == 3) {
fout << pref(stri) << '\n';
}
}
}