Pagini recente » Cod sursa (job #1740669) | Cod sursa (job #98696) | Cod sursa (job #2211461) | Cod sursa (job #1310639) | Cod sursa (job #2307513)
#include <cstdio>
#include <cstring>
#define SIGMA 26
using namespace std;
class Node{
public:
int nrap, nrc;
Node *fii[SIGMA];
Node(){
for(int i = 0; i < SIGMA; i++)
fii[i] = NULL;
nrap = nrc = 0;
}
};
Node* insert_trie(Node* node, char *s)
{
if(node == NULL) node = new Node;
node-> nrap++;
if(s[0] == '\0')
node-> nrc++;
else
node-> fii[s[0] - 'a'] = insert_trie(node-> fii[s[0] - 'a'], s + 1);
return node;
}
Node* delete_trie(Node* node, char *s)
{
if(s[0] == '\0')
{
node-> nrap--;
node-> nrc--;
if(node-> nrap==0){
delete node;
return NULL;
}
return node;
}
node-> fii[s[0]-'a'] = delete_trie(node-> fii[s[0] - 'a'], s + 1);
node-> nrap--;
if (node-> nrap==0)
{
delete node;
return NULL;
}
return node;
}
int nr_ap(Node* node, char *s)
{
if(node == NULL)
return 0;
if(s[0] == '\0')
return node-> nrc;
return nr_ap(node-> fii[s[0] - 'a'], s + 1);
}
int bestPref(Node* node, char *s)
{
if(node == NULL)
return -1;
if(s[0] == '\0')
return 0;
return 1 + bestPref(node-> fii[s[0] - 'a'], s + 1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
Node* trie = NULL;
int op;
char s[21];
while(scanf("%d", &op) != EOF)
{
scanf(" ");
scanf("%s", &s);
scanf("\n");
if(op == 0) trie = insert_trie(trie, s);
else if(op == 1) trie = delete_trie(trie, s);
else if(op == 2) printf("%d\n", nr_ap(trie, s));
else printf("%d\n", bestPref(trie, s));
}
return 0;
}