Cod sursa(job #2443675)

Utilizator AlexNeaguAlexandru AlexNeagu Data 29 iulie 2019 10:23:26
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct Trie {
	int cnt_words, cnt_sons;
	Trie *sons[30];
	Trie() {
		cnt_words = cnt_sons = 0;
		memset(sons, 0, sizeof(sons));
	}
};
Trie *cap = new Trie;
char s[50];
int operation, t;

void Insert(Trie *nod , char *a) {
	if (*a == '\n') {
       nod -> cnt_words++;
       return;
	}
	if (nod -> sons[ *a - 'a'] == 0) {
		nod -> sons[ *a - 'a'] = new Trie;
		nod -> cnt_sons++;
	}
	Insert(nod -> sons[*a - 'a'], a + 1);
}
int Delet(Trie *nod, char *a) {
	if (*a == '\n') {
		nod -> cnt_words--;
	}
	else 
	if (Delet(nod -> sons[*a - 'a'] , a + 1)) {
		nod -> sons[*a - 'a'] = 0;
		nod -> cnt_sons--;
	}
	if (nod -> cnt_words == 0 && nod -> cnt_sons == 0 && nod != cap)
	{
		delete nod;
		return 1;
	}
	return 0;
}
int Find(Trie *nod, char *a) {
	if (*a == '\n') {
		return nod -> cnt_words;
	}
	if (nod -> sons[*a - 'a'])
		return Find(nod -> sons[*a - 'a'], a + 1);
	return 0;
}
int Prefix(Trie *nod, char *a, int len) {
	if (*a == '\n' || nod -> sons[*a - 'a'] == 0)
		return len;
	return Prefix(nod -> sons[*a - 'a'], a + 1, len + 1);
}
int main() {
	
	while (in.getline(s, sizeof(s))) {
		
        switch (s[0]) {
        	case '0' : Insert(cap, s + 2); 
        	case '1' : Delet(cap, s + 2);
        	case '2' : out << Find(cap, s + 2) << "\n";
        	case '3' : out << Prefix(cap, s + 2, 0) << "\n";
        }
	}
}