Pagini recente » Cod sursa (job #1087993) | Cod sursa (job #1783319) | Cod sursa (job #680907) | Cod sursa (job #1204720) | Cod sursa (job #3207595)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
struct Trie {
Trie *sons[26];
int cnt = 0, prefix = 0;
Trie() {
cnt = 0;
prefix = 0;
memset(sons, 0, sizeof(sons));
}
};
Trie *root = new Trie;
void add (Trie *root, char s[]) {
if (s[0] == NULL) {
++root -> cnt;
} else {
if (root -> sons[s[0] - 'a'] == NULL) {
root -> sons[s[0] - 'a'] = new Trie();
}
++root -> sons[s[0] - 'a'] -> prefix;
add(root -> sons[s[0] - 'a'], s + 1);
}
}
void del (Trie *root, char s[]) {
if (s[0] == NULL) {
--root -> cnt;
} else {
--root -> sons[s[0] - 'a'] -> prefix;
del(root -> sons[s[0] - 'a'], s + 1);
}
}
int countAparitii (Trie *root, char s[]) {
if (s[0] == NULL) {
return root -> cnt;
} else {
if (root -> sons[s[0] - 'a'] == NULL) {
return 0;
}
return (countAparitii(root -> sons[s[0] - 'a'], s + 1));
}
}
int longestPrefix (Trie *root, char s[], int k) {
if (s[0] == NULL) {
return k;
} else {
if (root -> sons[s[0] - 'a'] == NULL || root -> sons[s[0] - 'a'] -> prefix == 0) {
return k;
}
return longestPrefix(root -> sons[s[0] - 'a'], s + 1, k + 1);
}
}
int main() {
int op;
char s[21];
while (fin >> op >> s) {
if (op == 0) {
add(root, s);
} else if (op == 1) {
del(root, s);
} else if (op == 2) {
fout << countAparitii(root, s) << '\n';
} else if (op == 3) {
fout << longestPrefix(root, s, 0) << '\n';
}
}
}