Cod sursa(job #2239791)

Utilizator shantih1Alex S Hill shantih1 Data 11 septembrie 2018 21:09:05
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#define CH *ch-'a'

using namespace std;

int i,j,n;
char s[32],*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=='\n')
	{   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(ch<s+2)	return;
	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=='\n' || 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')   printf("%d\n",((*ch=='\n')?(nd->cnt):0));
		if(s[0]=='3')   printf("%d\n",int(ch-s-2));
		return;
	}
	prefx(nd->fii[CH], ch+1);
}

int main() {
	
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);
	
	while(fgets(s, 32, stdin)){
		prefx(T, s+2);
	}
	return 0;
}