Cod sursa(job #1019639)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 31 octombrie 2013 18:31:41
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
#include <iostream>
#define Nmax 200

using namespace std;

struct trie
{
	int no;
	int now;
	trie *d[26];

	trie()
	{
		no = 0;
		now = 0;
		for (int i = 0; i<26;++i)
			d[i] = NULL;
	}
};

void insert(trie *&p, char *x)
{
	if(!p)
		p = new trie;
	p->no++;
	if (strlen(x)==0)
	{
		p->now++;
		return;
	}
	insert(p->d[x[0]-'a'],x+1);
}

int noOfOccurences(trie *p, char *x)
{
	if (!p) return 0;
	if (strlen(x)==0) return p->now;
	return noOfOccurences(p->d[x[0]-'a'],x+1);
}

int maxPrefix(trie *p, char *x)
{
	if (!p) return 0;
	if (p->no <= 0) return 0;
	if (strlen(x)==0) return 1;
	return 1+maxPrefix(p->d[x[0]-'a'],x+1);
}

void remove(trie *p, char *x)
{
	if (!p) return;
	p->no--;
	if (strlen(x)==0){
		p->now--;
		return;
	}
	remove(p->d[x[0]-'a'],x+1);
}

int main()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);

	trie *root = new trie;

	int type;
	char c[Nmax];
	while(cin>>type)
	{
		cin>>c;
		if (type == 0) insert(root,c);
		if (type == 1) remove(root,c);
		if (type == 2) printf("%d\n", noOfOccurences(root,c));
		if (type == 3) printf("%d\n", maxPrefix(root,c)-1);
	}

	return 0;
}