Cod sursa(job #616668)

Utilizator razyelxrazyelx razyelx Data 13 octombrie 2011 01:00:27
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>

#define idx (s[i] - 'a')

using namespace std;

class Trie{
	
	vector<Trie*> letter;
	int words;
	int childs;
	
public:
	
	Trie(){
		letter.resize(26);
		for (int i = 0; i < 26; i++) letter[i] = 0;
		words = 0;
		childs = 0;
	}
	
	void add(string s) {		
		Trie *prev, *curent = this;
		char a;
		for (int i = 0; i < (int)s.length(); i++){
			a = s[i];
			if (curent->letter[idx] == 0) {				
				curent->letter[idx] = new Trie;
				curent->childs++;				
			}
			prev = curent;			
			curent = curent->letter[idx];	
		}
		curent->words++;			
	}	
	
	void rem(string s) {
		stack<Trie*> st;		
		Trie *curent = this;
		char a;
		for (int i = 0; i < (int)s.length(); i++){
			st.push(curent);
			curent = curent->letter[idx];
			a = s[i];
		}
		st.push(curent);		
		curent->words--;
		do {
			st.pop();	
			for (int i = 0; i < 26; i++)
				if ( st.top()->letter[i] == curent){
					for (int j = 0; j < 26; j++){
						delete curent->letter[j];
						curent->letter[j] = 0;
					}
					delete curent;
					st.top()->letter[i] = 0;
					curent = st.top();
					
					st.top()->childs--;
					break;
				}			
		} while ( st.top()->words == 0 && st.top()->childs == 0 && !st.empty());
	}
	
	int times(string s){
		Trie *prev, *curent = this;
		char a;
		for (int i = 0; i < (int)s.length(); i++){
			a = s[i];
			prev = curent;
			curent = curent->letter[idx];
		}		
		return curent->words;		
	}
	
	int longestPrefix(string s) {
		Trie *curent = this;
		int length = 0;
		for (int i = 0; i < (int)s.length() && curent; i++){
			if ( curent->letter[idx] != 0 ) length = i + 1;
			curent = curent->letter[idx];
		}	
		return length;		
	}
	
};
#include <iostream>

int main(){

	string s;
	int op;
	
	Trie *t = new Trie();
	
	ifstream fin("trie.in");
	ofstream fout("trie.out");
	
	fin >> op >> s;
	
	do {
		
		if (op == 0)
			t->add(s);
		if (op == 1)
			t->rem(s);
		if (op == 2){
			int a = t->times(s);
			fout << a << '\n';
		}
		if (op == 3){
			int a = t->longestPrefix(s);
			fout << a << '\n';
		}
	
	}while ( fin >> op >> s);
	
	//delete t;
	
	return 0;
}