Cod sursa(job #1909785)

Utilizator lflorin29Florin Laiu lflorin29 Data 7 martie 2017 13:55:40
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

const int SIGMA = 26;
struct trie {
	trie *fii[SIGMA];
	int ap;
	trie() {
		ap = 0;
		memset(fii, 0, sizeof(fii));
	}
	int getAp(trie *&t) {
		int res = t->ap;

		for (int i = 0; i < SIGMA; ++i)
			if (t->fii[i])
				res -= t->fii[i]->ap;

		return res;
	}

	void baga(const string &that, int delta) {
		auto t = this;

		for (const auto &itr : that) {
			int pos = itr - 'a';

			if (!t->fii[pos])
				t->fii[pos] = new trie;

			t = t->fii[pos];
			t->ap += delta;
		}
	}
	int apare(const string &that) {
		auto t = this;

		for (const auto &itr : that) {
			int pos = itr - 'a';

			if (!t->fii[pos])
				return 0;

			t = t->fii[pos];
		}

		return getAp(t);
	}
	int LCP(const string &that) {
		auto t = this;
		int cnt = 0;

		for (const auto &itr : that) {
			int pos = itr - 'a';

			if (!t->fii[pos] or !t->fii[pos]->ap)
				return cnt;

			cnt++;
			t = t->fii[pos];
		}

		return cnt;
	}
};
int main() {
	ifstream cin("trie.in");
	ofstream cout("trie.out");

	int tip;
	string query;
	trie *T = new trie;

	while (cin >> tip) {
		cin >> query;

		if (tip == 0)
			T->baga(query, 1);
		else if (tip == 1)
			T->baga(query, -1);
		else if (tip == 2)
			cout << T->apare(query) << '\n';
		else cout << T->LCP(query) << '\n';
	}

	return 0;
}