Cod sursa(job #2732187)

Utilizator om6gaLungu Adrian om6ga Data 28 martie 2021 19:56:44
Problema Trie Scor 0
Compilator c-32 Status done
Runda Arhiva educationala Marime 2.72 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[115000]; // chunk of 115000 nodes
int alloc_cnt = 1;
TrieNode *T = mem;
 
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) {
		//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) {
	int t = 0;
	while (1) {
		if (*s < 'a' || node->child[CH] == 0)
		    return t;
		if (node->child[CH]) {
			node = node->child[CH];
			s++;
			t++;
		}
	}
}

char output[200000];
int oindex;
char input[2000000];
int iindex;

int main() {
	char line[ 32 ];
	char *s;
	int i, nr;
 
    freopen( "trie.in", "r", stdin );
	freopen( "trie.out", "w", stdout );
	//freopen( "grader_test20.in", "r", stdin );
	//freopen( "grader_test20.out", "w", stdout );
	
	T->freq = 1;
 
/*	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 );
	}*/
	
	iindex = read(0, input, 2000000);
	while (1) {
		op = input[i];
		s = input+i+2;
		i += 3;
		while (1) {
			if (input[i] == '\n')
			    break;
			i++;
		}
		input[i++] = '\0';
		switch(op) {
			case '0':
				add(T, s);
			    break;
			case '1':
				rm(T, s);
			    break;
			case '2':
				nr = query(T, s);
				oindex += sprintf(output+oindex, "%d\n", nr);
			    break;
			case '3':
				nr = prefix(T, s);
				oindex += sprintf(output+oindex, "%d\n", nr);
			    break;
		}
		if (i >= iindex)
	        break;
	}
	write(1, output, oindex);
	
	
	return 0;
}