Cod sursa(job #2637833)

Utilizator ViAlexVisan Alexandru ViAlex Data 25 iulie 2020 11:06:28
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include<iostream>
#include<fstream>
using namespace std;

#define NUMCHARS 26

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


int charToInt(char a){
	return a-'a';
}

struct node{
	node*children[NUMCHARS];
	char data;
	int occurences;
	int num_children;
	node(char value):data(value),occurences(0),num_children(0){
		for(int i=0;i<NUMCHARS;i++)
			children[i]=nullptr;
	}
};

node*root;

void dfs(node*here,string formed){//just for debugging
	if(here->occurences){
		cout<<formed<<" "<<here->occurences<<endl;
	}

	for(int i=0;i<NUMCHARS;i++){
		char ch='a'+i;
		if(here->children[i])
			dfs(here->children[i],formed+ch);
	}

}

void insert(const std::string&to_insert){
	node*here=root;
	for(char a:to_insert){
		int index=charToInt(a);
		if(!here->children[index]){
			here->children[index]=new node(a);
		}
		here=here->children[index];
		here->num_children++;
	}
	here->occurences++;
}

void rec_erase(const std::string&to_erase,int index,node*here){
	char char_here=to_erase[index];

	node* next=here->children[charToInt(char_here)];
	next->num_children--;

	if(index+1<to_erase.size()){
		rec_erase(to_erase,index+1,next);
	}
	else next->occurences--;


	if(next->num_children==0){
		delete next;
		here->children[charToInt(char_here)]=nullptr;
	}
}

void erase(const std::string&to_erase){
	rec_erase(to_erase,0,root);
}

int getNumOccurences(const std::string&to_query){
	node*here=root;
	for(char a:to_query){
		int index=charToInt(a);
		if(!here->children[index]){
			return 0;	
		}
		here=here->children[index];
	}
	return here->occurences;
}

int getMaxPrefix(const std::string&to_query){
	int prefix=0;
	node*here=root;
	for(char a:to_query){
		int index=charToInt(a);
		if(!here->children[index]){
			return prefix;	
		}
		here=here->children[index];
		prefix++;
	}
	return prefix;
}


void read(){
	int query;
	string to_query;

	while(in>>query>>to_query){
		if(query==0){
			insert(to_query);
		}
		else if(query==1){
			erase(to_query);
		}
		else if(query==2){
			out<<getNumOccurences(to_query)<<'\n';
		}
		else{
			out<<getMaxPrefix(to_query)<<"\n";
		}
	}
}
int main(){
	root=new node(' ');
	read();

	return 0;
}