Cod sursa(job #1463918)

Utilizator tain1234andrei laur tain1234 Data 21 iulie 2015 20:14:31
Problema Trie Scor 45
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++; int k = 0;
		while (i < b.size() && temp != NULL){
			if (temp->nr>1 || temp->marker  && temp->info != b[b.size() - 1]){ 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 == 1) temp->count--;
				}
				else{
					i--;
					int p = k;
					node* tmp4 = temp2;
					node* tmp2 = temp2->child[b[k] - 'a'];
					while (tmp2 != NULL && k < b.size()){
						temp2 = tmp2;
						if (k < b.size() - 1)k++;
						tmp2 = tmp2->child[b[k] - 'a'];
						delete temp2;
					}
					tmp4->child[b[p] - 'a'] = NULL;
				}
			}
		}
	}
	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;
		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();
}