Pagini recente » Cod sursa (job #1244929) | Cod sursa (job #1775142) | Cod sursa (job #1963970) | Cod sursa (job #1300898) | Cod sursa (job #673894)
Cod sursa(job #673894)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Trie *Trie;
struct Trie {
Trie next[26];
unsigned int cnt;
unsigned int cut;
};
Trie newTrie()
{
Trie t = malloc(sizeof (struct Trie));
memset(t, 0, sizeof (struct Trie));
return t;
}
void deleteTrie(Trie *t)
{
if (!t) return;
if (!(*t)) return;
Trie *end = (*t)->next + 26;
Trie *p = (*t)->next;
while (p != end) deleteTrie(p);
*t = 0;
}
void addWord(Trie *t, const char *w)
{
if (!w || !t) return;
if (!(*t)) *t = newTrie();
if (*w) {
addWord(&(*t)->next[(*w) - 'a'], w+1);
++(*t)->cut;
} else {
++(*t)->cnt;
}
}
void delWord(Trie *t, const char *w)
{
if (!w || !t) return;
if (!(*t)) return;
if (*w) {
delWord(&(*t)->next[(*w) - 'a'], w+1);
--(*t)->cut;
} else {
--(*t)->cnt;
}
}
unsigned int countWord(Trie t, const char *w)
{
if (!w || !t) return 0;
if (!(*w)) return t->cnt;
return countWord(t->next[(*w) - 'a'], w+1);
}
unsigned int matchWord(Trie t, const char *w)
{
if (!w || !t || !(*w)) return 0;
if (!t->next[(*w) - 'a']) return 0;
if (t->cut < 2) return 0;
return 1 + matchWord(t->next[(*w) - 'a'], w+1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
char w[22];
char o;
Trie t = 0;
while (scanf("%c %s\n", &o, w) == 2) {
switch (o) {
case '0':
addWord(&t, w);
break;
case '1':
delWord(&t, w);
break;
case '2':
printf("%u\n", countWord(t, w));
break;
case '3':
printf("%u\n", matchWord(t, w));
break;
default:
break;
}
}
fclose(stdin);
fclose(stdout);
return 0;
}