Cod sursa(job #2924413)

Utilizator IanisBelu Ianis Ianis Data 1 octombrie 2022 23:39:47
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
#include <bits/stdc++.h>
ifstream fin("trie.in");
ofstream fout("trie.out");
#endif

struct Node {
	char c;
	Node *children[26];
	Node *parent;
	int freq, cnt;
	Node(Node *p) {
		c = 0;
		cnt = 0;
		freq = false;
		parent = p;
		for (int i = 0; i < 26; i++)
			children[i] = nullptr;
	}
};

int t;
string s;
Node *root;

void update1(const string &s) {
	Node *node = root;
	for (auto c : s) {
		c -= 'a';
		if (!node->children[c]) {
			node->children[c] = new Node(node);
			node->children[c]->c = c;
			node->cnt++;
		}
		node = node->children[c];
	}
	node->freq++;
}

void update2(const string &s) {
	Node *node = root;
	for (auto c : s) {
		c -= 'a';
		node = node->children[c];
	}
	node->freq--;
	if (node->freq)
		return;
	while (node->parent && (node->cnt == 0 && node->freq == 0)) {
		Node *p = node->parent;
		p->children[node->c] = nullptr;
		delete node;
		p->cnt--;
		node = p;
	}
}

int query1(const string &s) {
	Node *node = root;
	for (auto c : s) {
		c -= 'a';
		if (!node->children[c])
			return 0;
		node = node->children[c];
	}
	return node->freq;
}

int query2(const string &s) {
	Node *node = root;
	int ans = 0;
	for (auto c : s) {
		c -= 'a';
		if (!node->children[c])
			return ans;
		ans++;
		node = node->children[c];
	}
	return ans;
}

int32_t main() {
	root = new Node(nullptr);

	while (fin >> t >> s) {
		if (t == 0)
			update1(s);
		else if (t == 1)
			update2(s);
		else if (t == 2)
			fout << query1(s) << '\n';
		else
			fout << query2(s) << '\n';
	}

	return 0;
}