Pagini recente » Cod sursa (job #2844790) | Cod sursa (job #127381) | Cod sursa (job #1017752) | Cod sursa (job #1023286) | Cod sursa (job #2929396)
#include <bits/stdc++.h>
typedef struct TrieStruct {
int endHere, contained;
struct TrieStruct *next[26];
}Trie;
inline void addTrie(Trie *crtNode, char *word) {
++ (crtNode -> contained);
if (*word == 0) {
++ (crtNode -> endHere);
return;
}
short nextIndex = *word - 'a';
if ((crtNode -> next[nextIndex]) == NULL)
(crtNode -> next[nextIndex]) = (Trie*)calloc(1, sizeof(Trie));
addTrie((crtNode -> next[nextIndex]), word + 1);
}
inline void removeTrie(Trie *crtNode, char *word) {
-- (crtNode -> contained);
if (*word == NULL) {
-- (crtNode -> endHere);
return;
}
short nextIndex = *word - 'a';
removeTrie((crtNode -> next[nextIndex]), word + 1);
if (((crtNode -> next[nextIndex]) -> contained) == 0) {
free((crtNode -> next[nextIndex]));
(crtNode -> next[nextIndex]) = NULL;
}
}
inline int appearedTrie(Trie *crtNode, char *word) {
if (*word == 0) {
return (crtNode -> endHere);
}
short nextIndex = *word - 'a';
if ((crtNode -> next[nextIndex]) == NULL)
return 0;
return appearedTrie((crtNode -> next[nextIndex]), word + 1);
}
inline int longestCommonPrefix(Trie *crtNode, char *word) {
if (*word == 0)
return 0;
short nextIndex = *word - 'a';
if ((crtNode -> next[nextIndex]) == NULL)
return 0;
return 1 + longestCommonPrefix((crtNode -> next[nextIndex]), word + 1);
}
char word[21];
int main() {
std :: ios_base :: sync_with_stdio(0);
std :: ifstream fin("trie.in");
std :: ofstream fout("trie.out");
fin >> std :: skipws;
char task;
Trie *trie = (Trie*)calloc(1, sizeof(Trie));
while (fin >> task) {
fin >> word;
switch (task) {
case '0': {
addTrie(trie, word);
break;
}
case '1': {
removeTrie(trie, word);
break;
}
case '2': {
fout << appearedTrie(trie, word) << '\n';
break;
}
case '3': {
fout << longestCommonPrefix(trie, word) << '\n';
break;
}
}
}
fin.close();
fout.close();
return 0;
}