Pagini recente » Cod sursa (job #560416) | Cod sursa (job #692535) | Cod sursa (job #395359) | Cod sursa (job #2732038) | Cod sursa (job #1523659)
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
struct node
{
string word;
int appearances;
int nr;
node *suffixes[26];
node()
{
nr = 0;
appearances = 0;
memset(suffixes, 0, sizeof(suffixes));
}
};
node *p;
void insert(node *n, string w)
{
if (w.empty())
{
n -> nr += 1;
n -> appearances += 1;
return;
}
if (n -> suffixes[w[0] - 'a'] == 0)
{
n -> suffixes[w[0] - 'a'] = new node;
n -> suffixes[w[0] - 'a'] -> word = n -> word + w[0];
}
n -> nr += 1;
insert(n -> suffixes[w[0] - 'a'], w.substr(1));
}
void del(node *n, string w)
{
if (w.length() == 1)
{
n -> suffixes[w[0] - 'a'] -> nr -= 1;
n -> suffixes[w[0] - 'a'] -> appearances -= 1;
if (n -> suffixes[w[0] - 'a'] -> nr == 0)
{
n -> suffixes[w[0] - 'a'] = 0;
delete n -> suffixes[w[0] - 'a'];
}
return;
}
del(n -> suffixes[w[0] - 'a'], w.substr(1));
n -> suffixes[w[0] - 'a'] -> nr -= 1;
if (n != p and n -> suffixes[w[0] - 'a'] -> nr == 0)
{
n -> suffixes[w[0] - 'a'] = 0;
delete n -> suffixes[w[0] - 'a'];
}
}
int appear(node *b, string w)
{
if (w.empty())
return b -> appearances;
if (b -> suffixes[w[0] - 'a'])
return appear(b -> suffixes[w[0] - 'a'], w.substr(1));
return 0;
}
int prefix(node *b, string w)
{
if (w.empty())
return 0;
if (b -> suffixes[w[0] - 'a'] == 0)
return 0;
return 1 + prefix(b -> suffixes[w[0] - 'a'], w.substr(1));
}
int main()
{
string s;
int op;
node base;
ifstream mama("grader_test9.in");
ofstream tata("trie.out");
base.nr = 0;
p = &base;
while (mama >> op >> s)
{
if (op == 0)
insert(&base, s);
else if (op == 1)
del(&base, s);
else if (op == 2)
tata << appear(&base, s) << '\n';
else if (op == 3)
tata << prefix(&base, s) << '\n';
}
return 0;
}