Cod sursa(job #341126)

Utilizator Bogdan_tmmTirca Bogdan Bogdan_tmm Data 17 august 2009 16:26:14
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include<fstream>
#include<string>
using namespace std;
#define FOR(it,s) for(string ::iterator it=s.begin();it!=s.end();it++)
class trie
{
private:
	struct node
	{
		int cuv,pref;
		node *c['z'-'a'+1];
		node()
		{
			cuv=pref=0;
			memset(c,0,sizeof(c));
		}
	};
public:
	node *Rad;
	trie()
	{
		Rad=new node;
	}
	void Add(string str)
	{
		node *cur=Rad;
		cur->pref++;
		FOR(it,str)
		{
			if(cur->c[*it-'a']==0)
				cur->c[*it-'a']=new node;
			cur=cur->c[*it-'a'];
			cur->pref++;
		}
		cur->cuv++;
	}
	void Delete(string str)
	{
		node *cur=Rad,*prev;
		cur->pref--;
		int t=1;
		for(int i=0;i<(int)str.size();i++)
		{
			prev=cur;
			cur=cur->c[str[i]-'a'];
			cur->pref--;
			if(cur->pref==0)
			{
				t=0;
				prev->c[str[i]-'a']=0;
				for(i++;i<(int)str.size();i++)
				{
					node *aux=cur;
					cur=cur->c[str[i]-'a'];
					delete aux;
				}
			}
		}
		if(t)
			cur->cuv--;
	}
	int Nr(string str)
	{
		node *cur=Rad;
		FOR(it,str)
		{
			if(cur->c[*it-'a']==0)
				return 0;
			cur=cur->c[*it-'a'];
		}
		return cur->cuv;
	}
	int Lng(string str)
	{
		node *cur=Rad;
		for(int i=0;i<(int)str.size();i++)
		{
			if(cur->c[str[i]-'a']==0)
				return i;
			cur=cur->c[str[i]-'a'];
		}
		return str.size();
	}
} Trie;
int main()
{
	ifstream f("trie.in");
	ofstream g("trie.out");
	int nr;
	string s;
	while(f>>nr)
	{
		f>>s;
		switch(nr)
		{
		case 0 : Trie.Add(s); break;
		case 1 : Trie.Delete(s);break;
		case 2 : g<<Trie.Nr(s)<<'\n';break;
		case 3 : g<<Trie.Lng(s)<<'\n';break;
		}
	}
	return 0;
}