Pagini recente » Cod sursa (job #2225697) | Cod sursa (job #1581593) | Cod sursa (job #1764724) | Cod sursa (job #1090036) | Cod sursa (job #1219928)
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
struct Trie {
int cnt, child_cnt;
Trie * child[26];
Trie() {
cnt = child_cnt = 0;
memset(child, 0, sizeof(child));
}
};
Trie *T = new Trie;
void add_word(Trie *nod, const char *s);
int del_word(Trie *nod, const char *s);
int count_word(Trie *nod, const char *s);
int max_prefix(Trie *nod, const char *s, int len);
void print_trie(Trie *nod, int offset, char c);
int main()
{
ifstream f ("trie.in");
ofstream g ("trie.out");
int t;
string s;
while (f >> t)
{
f >> s;
switch(t) {
case 0: add_word(T, s.c_str()); break;
case 1: del_word(T, s.c_str()); break;
case 2: g << count_word(T, s.c_str()) << '\n'; break;
case 3: g << max_prefix(T, s.c_str(), 0) << '\n'; break;
}
}
// print_trie(T, 2, '#');
return 0;
}
void add_word(Trie *nod, const char *s) // done!
{
if (*s == '\0')
{
(nod->cnt)++;
return;
}
else
{
int i = *s - 'a';
if (nod->child[i] == 0)
{
nod->child[i] = new Trie;
nod->child_cnt ++;
}
add_word(nod->child[i], s+1);
}
}
int count_word(Trie *nod, const char *s) // done!
{
if (*s == '\0')
return nod->cnt;
int i = *s - 'a';
if (nod->child[i])
return count_word(nod->child[i], s+1);
return 0;
}
int max_prefix(Trie *nod, const char *s, int len) // done!
{
if (*s == '\0')
return len;
int i = *s - 'a';
if (nod->child[i] == 0)
return len;
return max_prefix(nod->child[i], s+1, len+1);
}
int del_word(Trie *nod, const char *s)
{
if (*s == '\0')
{
nod->cnt --;
}
else
{
int i = *s - 'a';
if (del_word(nod->child[i], s+1))
{
nod->child_cnt --;
nod->child[i] = 0;
}
}
if (nod->cnt == 0 && nod->child_cnt == 0 && nod != T)
{
delete nod;
return 1;
}
return 0;
}
void print_trie(Trie *nod, int offset, char c) // done!
{
cout << string(offset, ' ') << c << ": " << nod->cnt << '\n';
if (nod->child_cnt == 0)
return;
else for (int i = 0; i < 26; i++)
{
if (nod->child[i] != 0)
{
print_trie(nod->child[i], offset + 2, i + 'a');
}
}
}