Pagini recente » Cod sursa (job #1730531) | Cod sursa (job #1533472) | Cod sursa (job #2565641) | Cod sursa (job #2738441) | Cod sursa (job #1523675)
#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));
}
bool del(node *n, string w)
{
if (w.empty())
{
if (!(n -> nr -= 1))
{
delete n;
return 1;
}
n -> appearances -= 1;
return 0;
}
if (del(n -> suffixes[w[0] - 'a'], w.substr(1)))
n -> suffixes[w[0] - 'a'] = 0;
if (n != p and !(n -> nr -= 1))
{
delete n;
return 1;
}
return 0;
/*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("trie.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;
}