Cod sursa(job #1463421)

Utilizator DacianBocea Dacian Dacian Data 20 iulie 2015 21:57:54
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <fstream>
#include <iostream>
#include <string>
#include <map>
using namespace std;
class node{
public:
	char info;
	bool marker;
	int count;
	map<char, node*> child;
	node(){
		info = ' ';
		marker = false;
		count = 0;
	}
	node(char& c){
		info = c;
		marker = false;
		count = 0;
	}
};
class trie{
public:
	int f;
	node* root;
	trie(){
		f = 0;
		root = new node();
	}
	void del(string &b){
		int i = 0;
		node* temp = root->child[b[i]];
		i++;
		while (i < b.size() && temp != NULL){
			temp = temp->child[b[i]];
			i++;
		}
		if (temp->count>1) temp->count--;
		else{
			if (temp->child.size() > 0) {
				temp->marker = false; if (temp->count == 1) temp->count--;
			}
			else{
				i--;
				int k=0,p,j = 0;
				node* tmp4;
				node* tmp3=root;
				node* tmp2 = root->child[b[j]];
				j++;
				while (j < b.size() && tmp2 != temp){
					if (tmp2->child.size()>1 || tmp2->marker){ tmp3 = tmp2; k = j; }
					tmp2 = tmp2->child[b[j]];
					j++;
				}
				tmp4 = tmp3;
				p = k;
				tmp2 = tmp3->child[b[k]];
				while (tmp2 != NULL && k < b.size()){
					tmp3 = tmp2;
					k++;
					tmp2 = tmp2->child[b[k]];
					delete tmp3;
				}
				tmp4->child[b[p]] = NULL;
			}
		}
	}
	int counts(string &b){
		int i = 0;
		node* temp =root->child[b[i]];
		i++;
		while (i < b.size() && temp != NULL){
			temp=temp->child[b[i]];
			i++;
		}
		if (temp != NULL)return temp->count;
		else return 0;
	}
	int cl(string& b){
		string pref ="";
		node* tmp = root->child[b[0]];
		int j = 0, i = 1;
		if (tmp != NULL)j++;
		while (tmp != NULL){
			tmp = tmp->child[b[i]];
			if (tmp != NULL)j++;
			i++;
		}
		return j;
	}
	void add(string& b){
		node* temp=root;
		int i = 0;
		while (i < b.size()){
			if (temp->child[b[i]] != NULL)
				temp = temp->child[b[i]];
			else{
				f++;
				temp->child[b[i]] = new node(b[i]);
				temp = temp->child[b[i]];
			}
			i++;
		}
		temp->marker = true; temp->count++;
	}
};
int main(){
		trie t;
		ifstream f("trie.in");
		ofstream of("trie.out");
		int b; string c;
		while (f>>b>>c){
			if (b == 0) t.add(c);
			else if (b == 1)t.del(c);
			else if (b == 2) of << t.counts(c) << endl;
			else if (b == 3)of << t.cl(c) << endl;
		}

}