Cod sursa(job #1774085)

Utilizator RobertSSamoilescu Robert RobertS Data 8 octombrie 2016 15:38:26
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.12 kb
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <vector>

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Node {
	int app, endings;
	vector<Node*> sons;

	Node() {
		sons = vector<Node*>(26, NULL);
		app = 0;
		endings = 0;
	}


};

Node *trie, *cpy_trie;

void add_word(string word) {

	trie->endings++;

	for (size_t i = 0; i < word.length(); i++) {
		int letter = int(word[i] - 'a');

		if (trie->sons[letter] == NULL) {
			trie->sons[letter] = new Node();
		}

		
		trie->sons[letter]->endings++;
		trie = trie->sons[letter];
	}


	trie->app++;

}

void remove_word(Node **trie, string word) {
 


	if (word.empty()) {
		
		(*trie)->endings--;
		(*trie)->app--;
		
		if ((*trie)->endings == 0) {
			delete *trie;
			*trie = NULL;
		}
		
	} else {
		remove_word( &(*trie)->sons[word[0] - 'a'], word.substr(1));
		
		(*trie)->endings--;
		if ((*trie)->endings == 0) {
			delete *trie;
			*trie = NULL;
		}
			
	}

}

int get_app_nr(string word) {

	for (size_t i = 0; i < word.length(); i++)
	    {
	        int letter = int(word[i] - 'a');
	 
	        if (trie->sons[letter]) {
	            trie = trie->sons[letter];
	        } else return 0;
	    }
 
 	
    return trie->app;
}

int get_prefix(string word) {
	int prefix = 0;
 
    for (size_t i = 0; i < word.length(); i++)
    {
 	
        int letter = int(word[i] - 'a');
        if (trie->sons[letter])
        {
            trie = trie->sons[letter];
            prefix = i + 1;
        }
        else break;
    }
 
    return prefix;

}

void process_command(int command, string word) {

	if (command == 0)
		add_word(word);

	if (command == 1)
		remove_word(&trie, word);

	if (command == 2)
		fout << get_app_nr(word) << "\n";

	if (command == 3)
		fout << get_prefix(word) << "\n"; 

}

int main() {


	int const MAX = 30;
	char line[MAX];


	trie = new Node();
	cpy_trie = trie;


	while (fin.getline(line,MAX)) {
		char delim[] = " ";
		int command = atoi(strtok(line, delim));
		string word(strtok(NULL, delim));

		process_command(command, word);

		trie = cpy_trie;

	}


	fin.close();
	fout.close();
	return 0;
}