Cod sursa(job #2732156)

Utilizator om6gaLungu Adrian om6ga Data 28 martie 2021 19:36:58
Problema Trie Scor 100
Compilator c-32 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <stdio.h>
#include <stdlib.h>

#define CH (*s - 'a')

struct TrieNode {
	struct TrieNode *child[26];
	char childrenCount; // how many children it has - presumably useful for deletion
	short int freq; // nr of appearances of the word formed by the characters belonging to the path starting at root and ending here
};

typedef struct TrieNode TrieNode;
 
TrieNode mem[120000]; // chunk of 120000 nodes
int alloc_cnt;
TrieNode T;

void add(TrieNode *node, char *s) {  // assume word '\0' terminated
	if (s[0] < 'a') { // have hit either '\0' or '\n'
		node->freq++;
		return;
	}
	if (node->child[CH] == NULL) {
		//node->child[CH] = calloc(1, sizeof(struct TrieNode));
		node->child[CH] = &mem[alloc_cnt];
		alloc_cnt++;
		node->childrenCount++;
	}
	add(node->child[CH], s+1);
}

int rm(TrieNode *node, char *s) {
	if  (s[0] < 'a') {
        node->freq--;
	}
	else if (rm(node->child[CH], s+1)) {
		node->child[CH] = 0;
		node->childrenCount--;
	}
	if (node->freq == 0 && node->childrenCount == 0 && node != &T) {
		//free(node);
		return 1;
	}
	return 0;
}

int query(TrieNode *node, char *s) {
	while (1) {
		if (*s < 'a')
		    return node->freq;
		if (node->child[CH]) {
			node = node->child[CH];
			s++;
		}
		else
		    return 0;
	}
	return 0;
}

int prefix(TrieNode *node, char *s, int k) {
	short int t = 0;
	while (1) {
		if (*s < 'a' || node->child[CH] == 0)
		    return t;
		if (node->child[CH]) {
			node = node->child[CH];
			s++;
			t++;
		}
	}
}
 
int main() {
	char line[ 32 ];
	char *s;
 
    freopen( "trie.in", "r", stdin );
	freopen( "trie.out", "w", stdout );
	//freopen( "grader_test20.in", "r", stdin );
	//freopen( "grader_test20.out", "w", stdout );
 
	fgets( line, 32, stdin );
 
	while( !feof( stdin ) ) {
		s = line+2;
		switch( line[0] ) {
			case '0': add( &T, s ); break;
			case '1': rm( &T, s ); break;
			case '2': printf( "%d\n", query( &T, s ) ); break;
			case '3': printf( "%d\n", prefix( &T, s, 0 ) ); break;
		}
		fgets( line, 32, stdin );
	}
	return 0;
}