Cod sursa(job #2881554)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 30 martie 2022 16:18:39
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "trie";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");


char s[100000];

class TrieNode {

public:
	int apcuv;
	int fr;
	TrieNode *leg[26];

	TrieNode() {

		apcuv = fr = 0;
		for (int i = 0; i < 26; ++i)
			leg[i] = NULL;
	}

	void ins(char *w) {
		if (*w == 0)
			this->apcuv++;
		else {
			if (this->leg[*w - 'a'] == NULL) {
				this->leg[*w - 'a'] = new TrieNode;
			}
			this->leg[*w - 'a']->ins(w + 1);
			this->leg[*w - 'a']->fr++;

		}
	}

	void del(char *w) {
		if (*w == 0) {
			this->apcuv--;
		}
		else {
			this->leg[*w - 'a']->del(w + 1);
			this->leg[*w - 'a']->fr--;
		}
	}

	int nrap(char *w) {
		if (*w == 0) {
			return this->apcuv;
		}
		else {
			if (this->leg[*w - 'a'] == NULL)
				return 0;
			return this->leg[*w - 'a']->nrap(w + 1);
		}
	}
	int lcp(char *w) {
		if (*w == 0) {
			return 0;
		}
		else {
			if (this->leg[*w - 'a'] == NULL || this->leg[*w - 'a']->fr == 0)
				return 0;
			return 1 + this->leg[*w - 'a']->lcp(w + 1);
		}
	}


};

class Trie {

public:
	TrieNode *root;

	Trie() {
		this->root = new TrieNode;
	}

	void ins(char *w) {
		this->root->ins(w);
	}
	void del(char *w) {
		this->root->del(w);
	}
	int nrap(char *w) {
		return this->root->nrap(w);
	}
	int lcp(char *w) {
		return this ->root->lcp(w);
	}


} t;


int main() {
	int op;
	char s[100000];
	while (fin >> op >> s) {
		if (op == 0)
			t.ins(s);
		else if (op == 1)
			t.del(s);
		else if (op == 2)
			fout << t.nrap(s) << '\n';
		else
			fout << t.lcp(s) << '\n';
	}


	return 0;
}