Pagini recente » Cod sursa (job #2753110) | Cod sursa (job #727782) | Cod sursa (job #3256017) | Cod sursa (job #932923) | Cod sursa (job #2731408)
#include <stdio.h>
#include <stdlib.h>
#define CH (*s - 'a')
struct TrieNode {
struct TrieNode *parent;
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 120000 nodes
int alloc_cnt = 1;
TrieNode *T = mem; // first node in chunk we'll be using as root
/* 0 w - adauga o aparitie a cuvantului w in lista
1 w - sterge o aparitie a cuvantului w din lista
2 w - tipareste numarul de aparitii ale cuvantului w in lista
3 w - tipareste lungimea celui mai lung prefix comun al lui w cu oricare cuvant din lista
Pentru toate operatiile, cuvantul w este format din maxim 20 de caractere din intervalul 'a'..'z'
Numarul total de operatii nu va depasi 100 000
Operatiile de tip 1 w vor aparea numai daca w apare cel putin o data in lista de cuvinte */
void add(TrieNode *node, char *s) { // assume word '\0' terminated
char ch;
while (1) {
ch = *s - 'a';
if (ch < 0) { // have hit either '\0' or '\n'
node->freq++;
return;
}
if (node->child[ch] == NULL) {
node->child[ch] = &mem[alloc_cnt++];
node->child[ch]->parent = node;
node->childrenCount++;
}
node = node->child[ch];
s++;
}
}
int rm(TrieNode *node, char *s) {
char ch;
while (1) {
ch = *s++ - 'a';
if (ch < 0) { // have hit either '\0' or '\n'
node->freq--;
break;
}
node = node->child[ch];
}
}
int query(TrieNode *node, char *s) {
char ch;
while (1) {
ch = *s - 'a';
if (ch < 0)
return node->freq;
if (node->child[ch]) {
node = node->child[ch];
s++;
}
else
return 0;
}
return 0;
}
int prefix(TrieNode *node, char *s) { short int t = 0;
char ch;
while (1) {
ch = *s - 'a';
if (ch < 0 || 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));
break;
}
fgets(line, 32, stdin);
}
//printf("alloc_cnt = %d\n", alloc_cnt);
return 0;
}