Cod sursa(job #1463987)

Utilizator tain1234andrei laur tain1234 Data 21 iulie 2015 23:21:45
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class node{
public:
	char info;
	bool marker;
	int count,nr;
	vector<node*> child;
	node(){
		nr=0;
		child.resize(26, NULL);
		info = ' ';
		marker = false;
		count = 0;
	}
	node(char& c){
		nr = 0;
		child.resize(26, NULL);
		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] - 'a'];
		node* temp2 = root;
		i = 1; int nr = b.size(), k = 0;
		while (i < nr && temp != NULL){
			if ((temp->nr>1 || temp->marker)){ temp2 = temp; k = i; }
			temp = temp->child[b[i] - 'a'];
			i++;
		}
		if (temp != NULL){
			if (temp->count > 1) temp->count--;
			else{
				if (temp->nr > 0) {
					temp->marker = false; 
					if (temp->count !=0) temp->count=0;
				}
				else{
					if (temp2 == root)k=0;
					int p= k;
					node* tmp4 = temp2;
					node* tmp2 = temp2->child[b[k] - 'a'];
					while (tmp2 != NULL && k < nr){
						temp2 = tmp2;
						if (k < nr- 1)k++;
						tmp2 = tmp2->child[b[k] - 'a'];
						delete temp2;
					}
					tmp4->child[b[p] - 'a'] = NULL;
					tmp4->nr--;
				}
			}
		}
	}
	int counts(string &b){
		int i = 0;
		node* temp =root->child[b[i]-'a'];
		i++;
		while (i < b.size() && temp != NULL){
			temp=temp->child[b[i]-'a'];
			i++;
		}
		if (temp != NULL)return temp->count;
		else return 0;
	}
	int cl(string& b){
		node* tmp = root->child[b[0]-'a'];
		int j = 0, i = 1;
		if (tmp != NULL)j++;
		while (tmp != NULL && i<b.size()){
			tmp = tmp->child[b[i]-'a'];
			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] - 'a'] != NULL)
				temp = temp->child[b[i] - 'a'];
			else{
				f++;
				temp->nr++;
				temp->child[b[i]-'a'] = new node(b[i]);
				temp = temp->child[b[i]-'a'];
			}
			i++;
		}
		 temp->marker = true; temp->count++;
	}
};
int main(){
	trie t;
	ifstream f("trie.in");
	ofstream of("trie.out");
	int b; string c;
	int i = 0;
	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; 
	}
	of.close();
	f.close();
}