Cod sursa(job #1538909)

Utilizator ArkinyStoica Alex Arkiny Data 29 noiembrie 2015 23:44:04
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include<fstream>
#include<string.h>
using namespace std;

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

struct Node
{
	Node *l[28];
	int number;
};

class Trie
{
private:
	Node *t;
public:
	Trie();
	void add(const char *c);
	void remove(const char *c);
	int print(const char *c);
	int length_com_pref(const char *c);
};

Trie::Trie()
{
	t = new Node;
	memset(t, 0, sizeof(Node));
}

void Trie::add(const char *c)
{
	Node *q = t;
	int i = 0;
	while (c[i]!='\0')
	{
		if (!q->l[c[i] - 'a'])
		{
			q->l[c[i] - 'a'] = new Node;
			memset(q->l[c[i] - 'a'], 0, sizeof(Node));
		}
		q = q->l[c[i] - 'a'];
		++i;
	}
	q->number += 1;
	
}

void Trie::remove(const char *c)
{
	Node *v[21],*q=t;
	int i = 0,j=0;
	v[0] = t;
	while (c[i] != '\0')
	{
		if (!q->l[c[i] - 'a'])
			return;
		v[i+1] = q->l[c[i] - 'a'];

		q = q->l[c[i] - 'a'];
		++i;
	}

	v[i]->number -= 1;


		while (i > 0 && v[i]->number == 0)
		{
			for (j = 0;j < 27;++j)
				if (v[i]->l[j] != 0)
					break;
			if (j == 27)
			{
				delete v[i];
				v[i - 1]->l[c[i - 1] - 'a'] = 0;
				--i;
			}
			else
				i = 0;
		}
	
}

int Trie::print(const char *c)
{
	Node *q = t;
	int i = 0;
	while (c[i] != '\0')
	{
		if (!q->l[c[i] - 'a'])
			return 0;
		q = q->l[c[i] - 'a'];
		++i;
	}
	return q->number;
}
int Trie::length_com_pref(const char *c)
{
	Node *q = t;
	int i = 0;
	while (c[i] != '\0')
	{
		if (!q->l[c[i] - 'a'])
			return i;
		q = q->l[c[i] - 'a'];
		++i;
	}
	return i;
}

char c[21];

int main()
{
	int op;
	Trie trie;
	while (in >> op)
	{
		in >> c;
		
		switch (op)
		{
		case 0:
			trie.add(c);
			break;
		case 1:
			trie.remove(c);
			break;
		case 2:
			out<<trie.print(c)<<'\n';
			break;
		case 3:
			out << trie.length_com_pref(c)<<'\n';
			break;
		}

	}
	return 0;
}