Cod sursa(job #1294142)

Utilizator deea101Andreea deea101 Data 17 decembrie 2014 00:04:27
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.56 kb
#include <fstream>
#include <string>
#include <cstring>

#define sizeAlpha 26

using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");

class Trie
{
	private:
		
		struct nod
		{
			int numSons;
			int numPref;
			int numWord;
			
			nod *sons[sizeAlpha];
			
			nod ()
			{
				numSons=numPref=numWord=0;
				memset(sons,NULL,sizeof(sons));
			}
		};
		
		nod *root;
		int s;
		
		
	public:
		
		Trie()
		{
			root=new nod;
		}
		
		void addWord (string w)
		{
			int i=0;
			int size=w.size();
			
			nod *currentNode=this->root;
			nod *newNode;
			
			int currentChar;

			while(w[i]!='\0')
			{
				currentChar=w[i]-'a';
			
				if(currentNode->sons[currentChar]==NULL)
					currentNode->sons[currentChar]=new nod;
				
				newNode=currentNode->sons[currentChar];
				newNode->numPref++;
				
				if(i+1 == size) newNode->numWord++;
				
				i++;
				currentNode=newNode;
			}
		}
		
		void eraseWord (string w)
		{
			int i=0;
			int size=w.size();
			
			nod *currentNode=this->root;
			nod *newNode;
			
			int currentChar;
			
			while(w[i]!='\0')
			{
				currentChar=w[i]-'a';
				
				if(currentNode->sons[currentChar]==NULL) break;
				
				newNode=currentNode->sons[currentChar];
				newNode->numPref--;
				
				if(i+1 == size) newNode->numWord--;
				
				i++;
				currentNode=newNode;
			}
		}
		
		int howMany (string w)
		{
			int i=0, count=0;
			int size=w.size();
			
			nod *currentNode=this->root;
			nod *newNode;
			
			int currentChar;
			
			while(w[i]!='\0')
			{
				currentChar=w[i]-'a';
				
				if(currentNode->sons[currentChar]==NULL) break;
				
				newNode=currentNode->sons[currentChar];
				if(i+1 == size) count=newNode->numWord;
				
				i++;
				currentNode=newNode;
			}
			return count;
		}
		
		int getPrefix (string w)
		{
			int i=0;
			string res;
			
			nod *currentNode=this->root;
			nod *newNode;
			
			int currentChar;
			
			while(w[i]!='\0')
			{
				currentChar=w[i]-'a';
				
				if(currentNode->sons[currentChar]==NULL) break;
				
				newNode=currentNode->sons[currentChar];
				if(newNode->numPref>0) res+=(currentChar+'a');
				else break;
				
				i++;
				currentNode=newNode;
			}
			return res.size();
		}
};

Trie t;
int main()
{
	int query;
	string w;
	while(f>>query)
	{
		f>>w;
		switch(query)
		{
			case 0:
				t.addWord(w); break;
			case 1:
				t.eraseWord(w); break;
			case 2:
				g<<t.howMany(w)<<'\n'; break;
			case 3:
				g<<t.getPrefix(w)<<'\n'; break;
		}
	}
	
}