Pagini recente » Cod sursa (job #1954927) | Cod sursa (job #271108) | Cod sursa (job #565856) | Cod sursa (job #2870844) | Cod sursa (job #845946)
Cod sursa(job #845946)
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
struct trie{
int nrs, nrw;
trie *leaf[26];
trie(){nrs=nrw=0; memset(leaf,0,sizeof(leaf));}
};
trie *root = new trie;
void func0 (char *x, trie *t) {
if (*x!='\n') {
if (t->leaf[*x-'a'] == 0) {
t->leaf[*x-'a'] = new trie;
t->nrs++;
}
func0(x+1, t->leaf[*x-'a']);
}
else
t->nrw++;
}
int func1 (char *x, trie *t) {
if (*x=='\n')
t->nrw--;
else if (func1(x+1, t->leaf[*x-'a'])) {
t->nrs--;
t->leaf[*x-'a'] = 0;
}
if (t!=root && t->nrs == 0 && t->nrw == 0) {
delete t;
return 1;
}
return 0;
}
int func2 (char *x, trie *t) {
if (*x!='\n')
return func2(x+1,t->leaf[*x-'a']);
else return t->nrw;
}
int func3 (char *x, trie *t, int lg) {
if (*x=='\n'||t->leaf[*x-'a']==0)
return lg;
else return func3(x+1,t->leaf[*x-'a'],lg+1);
}
int main() {
string s;
int i;
ifstream in("trie.in");
ofstream out("trie.out");
while (in>>i) {
in>>s;
s.append("\n");
if (i==0)
func0(&s[0],root);
if (i==1)
func1 (&s[0],root);
if (i==2)
out << func2(&s[0],root) << '\n';
if (i==3)
out << func3(&s[0],root,0) << '\n';
}
out.close();
return 0;
}