Cod sursa(job #2919095)

Utilizator AlexNeaguAlexandru AlexNeagu Data 15 august 2022 16:16:56
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <bits/stdc++.h>
using namespace std;
const int alphabet = 26;

ifstream in("trie.in");
ofstream out("trie.out");

struct nod {
	int val, words, nr_sons;
	nod *sons[alphabet];
	nod() : val(-1), words(0), nr_sons(0) {
		for(int i = 0; i < alphabet; ++i) {
			sons[i] = nullptr;
		}
	}
};

class Trie {
	nod *head;
public:
	Trie() {
		head = new nod;
	}
	void insert(nod *node, int pos, string &s) {
		if(pos == s.size()) {
			node -> words += 1;
			return;
		} 
		int ch = s[pos] - 'a';
		if(node -> sons[ch] == nullptr) {
			node -> sons[ch] = new nod;
			node -> nr_sons += 1;
		}
		insert(node -> sons[ch], pos + 1, s);
	}
	void insert(string &s) {
		insert(head, 0, s);
	}
	bool erase(nod *node, int pos, string s) {
		if(pos == s.size()) {
			node -> words--;
			if(!node -> words && !node -> nr_sons) {
				delete node;
				return true;
			}
			return false;
		}
		int ch = s[pos] - 'a';
		bool nxt_erase = erase(node -> sons[ch], pos + 1, s);
		if(nxt_erase) {
			node -> nr_sons -= 1;
			node -> sons[ch] = nullptr;
			if(!node -> words && !node -> nr_sons && node != head) {
				delete node;
				return true;
			}
		}
		return false;	
	}
	void erase(string &s) {
		erase(head, 0, s);
	}
	int word_freq(nod *node, int pos, string &s) {
		if(pos == s.size()) {
			return node -> words;
		}
		int ch = s[pos] - 'a';
		if(node -> sons[ch] == nullptr) {
			return 0;
		}
		return word_freq(node -> sons[ch], pos + 1, s);
	}
	int word_freq(string &s) {
		return word_freq(head, 0, s);
	}
	int longest_prefix(nod *node, int pos, string &s) {
		if(pos == s.size()) {
			return pos;
		}
		int ch = s[pos] - 'a';
		if(node -> sons[ch] == nullptr) {
			return pos;
		}
		return longest_prefix(node -> sons[ch], pos + 1, s);
	}
	int longest_prefix(string &s) {
		return longest_prefix(head, 0, s);
	}
};

Trie T;
int op;
string s;

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
    while(in >> op >> s) {
    	switch(op) {
    		case 0: {
    			T.insert(s); 
    			break;
    		}
    		case 1: {
    			T.erase(s); 
    			break;
    		}
    		case 2: {
    			cout << T.word_freq(s) << '\n'; 
    			break;
    		}
    		case 3: {
    			cout << T.longest_prefix(s) << '\n'; 
    			break;
    		}
    	}
    }
	return 0;
}