Cod sursa(job #2239749)

Utilizator shantih1Alex S Hill shantih1 Data 11 septembrie 2018 19:25:30
Problema Trie Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define CH *ch-'a'

using namespace std;

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

int i,j,n;
char s[30],*p;

struct trie
{
	int nrf,cnt;
	trie *fii[26],*t;
	trie ()
	{
		nrf=cnt=0;
		memset(fii, 0, sizeof(fii));
	}
};
trie *T = new trie;

void ins(trie *nd,char *ch)
{
	if(*ch=='\0')
	{   nd->cnt++;   return; }
	
	nd->fii[CH] = new trie;
	nd->fii[CH]->t=nd;
	nd->nrf++;
	ins(nd->fii[CH], ch+1);
}

void del(trie *nd,char *ch)
{
	if(nd->nrf==0 && nd->cnt==0)
	{
		trie *g=nd;
		nd->t->fii[CH]=0;
		nd->t->nrf--;
		delete[] nd;
		del(g->t, ch-1);
	}
}

void prefx(trie *nd,char *ch)
{
	if(*ch=='\0' || nd->fii[CH]==0)
	{
		if(s[0]=='0')   ins(nd, ch);
		if(s[0]=='1')   nd->cnt--,   del(nd, ch-1);
		if(s[0]=='2')   fout<<nd->cnt<<"\n";
		if(s[0]=='3')   fout<<ch-s-2<<"\n";
		return;
	}
	prefx(nd->fii[CH], ch+1);
}

int main() {
	
	while(fin.getline(s, 30))
		prefx(T, s+2);
}