Cod sursa(job #1534751)

Utilizator kassay_akosKassay Akos kassay_akos Data 23 noiembrie 2015 22:46:55
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

struct TRIE
{
	int nrSons, cnt;
	TRIE *son[26] ;

	TRIE() 
	{
		nrSons = cnt = 0;
		memset(son, 0, sizeof(son));
	};
};

TRIE *T = new TRIE();
int n;

void ins(TRIE *t, char *s);
int del(TRIE *t, char *s);
int query(TRIE *t, char *s);
int pre(TRIE *t, char *s, int k);

int main()
{
	freopen("trie.in", "r", stdin);
	freopen("trie.out", "w", stdout);
	char linie[32];

	fgets(linie, 32, stdin);

	while (!feof(stdin)) {
		switch (linie[0]) {
		case '0' :
			ins(T, linie + 2);
			break;
		case '1' :
			del(T, linie + 2);
			break;
		case '2' :
			printf("%d \n", query(T, linie + 2));
			break;
		case '3' :
			printf("%d \n", pre(T, linie + 2, 0));
			break;
		};
		fgets(linie, 32, stdin);
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}

inline int CHARACTER(char *s) { return *s - 'a'; };
//#define CH (*s - 'a')

void ins(TRIE *t, char *s){
	
	if (*s == '\n') {
		t->cnt++; return;
	}
	if (t->son[CHARACTER(s)] == 0) {
		t->son[CHARACTER(s)] = new TRIE;
		t->nrSons++;
	}
	ins(t->son[CHARACTER(s)], s + 1);
}

int del(TRIE *t, char *s) {
	if (*s == '\n') {
		t->cnt--;	
	}
	else if (del(t->son[CHARACTER(s)], s + 1)) {
		t->nrSons--;
		t->son[CHARACTER(s)] = 0;
	}
	if (t->cnt == 0 && t->nrSons == 0 && t != T) {
		delete t; return 1;
	}
	return 0;
}

int query(TRIE *t, char *s) {
	if (*s == '\n') return t->cnt;
	if (t->son[CHARACTER(s)] != 0 )
		return query(t->son[CHARACTER(s)], s + 1);
	return 0;
}

int pre(TRIE *t, char *s, int k) {
	if (*s == '\n') return k ;
	if (t->son[CHARACTER(s)] != 0)	return pre(t->son[CHARACTER(s)], s + 1, k + 1);
	else							return k;
}