Mai intai trebuie sa te autentifici.
Cod sursa(job #2018116)
Utilizator | Data | 3 septembrie 2017 15:38:50 | |
---|---|---|---|
Problema | Trie | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.85 kb |
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int litmax = 26;
const int nmax = 20;
struct Trie {
char lit;
int pref;
Trie* son[litmax];
};
Trie* root;
void addtrie(Trie* node, char* s) {
node->pref++;
if(*s != '\0') {
int pos = (*s - 'a');
if(node->son[pos] == NULL) {
node->son[pos] = new Trie();
node->son[pos]->lit = *s;
}
addtrie(node->son[pos], s + 1);
}
}
void deltrie(Trie* node, char* s) {
node->pref--;
if(*s != '\0') {
int pos = (*s - 'a');
deltrie(node->son[pos], s + 1);
}
}
int aparitii(Trie* node, char* s) {
if(*s == '\0') {
int prefsons = 0;
for(int i=0; i < litmax; i++)
if(node->son[i] != NULL)
prefsons += node->son[i]->pref;
return (node->pref - prefsons);
} else {
int pos = (*s - 'a');
if(node->son[pos] == NULL)
return 0;
return aparitii(node->son[pos], s + 1);
}
}
int prefix(Trie* node, char* s, int lung = 0) {
if(*s == '\0') {
if(node->pref == 0)
return -1;
else
return lung;
} else {
int pos = (*s - 'a');
if(node->son[pos] == NULL) {
if(node->pref == 0)
return -1;
else
return lung;
} else {
return max(prefix(node->son[pos], s + 1, lung + 1), node->pref != 0 ? lung : -1);
}
}
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
root = new Trie();
root->lit = '@';
root->pref = 0;
int n;
while(scanf("%d", &n) != EOF) {
char s[nmax + 3];
scanf("%s", s);
if(n == 0) {
addtrie(root, s);
} else if(n == 1) {
deltrie(root, s);
} else if(n == 2) {
printf("%d\n", aparitii(root, s));
} else {
printf("%d\n", prefix(root, s));
}
}
return 0;
}