Pagini recente » Cod sursa (job #1960583) | Cod sursa (job #125687) | Cod sursa (job #2376982) | Cod sursa (job #2941095) | Cod sursa (job #1813579)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct nod
{
int value, fin;
nod *next[26];
nod()
{
value = fin = 0;
for (int i =0; i<26; i++)
next[i] = 0;
}
} *root = new nod();
void add(string s)
{
nod *crt = root;
for(int i=0; i<s.size(); i++)
{
int nxt = s[i] - 'a';
if (crt ->next[nxt] == 0)
crt ->next[nxt] = new nod();
crt = crt ->next[nxt];
++crt -> value;
}
++ crt-> fin;
}
void remove(nod *root, char *s)
{
nod *lst = root;
int nxt = *s - 'a';
if (*s == '\0')
{
--lst -> fin;
return;
}
nod *crt = lst -> next[nxt];
remove(crt, s + 1);
--crt -> value;
if (crt -> value == 0)
{
delete crt;
lst -> next[nxt] = 0;
}
}
int occurs(string s)
{
nod *crt = root;
for(int i=0; i<s.size(); i++)
{
int nxt = s[i] - 'a';
if (crt -> next[nxt] == 0)
return 0;
crt = crt -> next[nxt];
}
return crt -> fin;
}
int prefix(string s)
{
nod *crt = root;
for(int i=0; i<s.size(); i++)
{
int nxt = s[i] - 'a';
if (crt -> next[nxt] == 0)
return i;
crt = crt -> next[nxt];
}
return s.size();
}
int main()
{
int act;
char s[30];
while (f >> act >> s)
{
if (act == 0) add(s);
else
if (act == 1) remove(root, s);
else
if (act == 2) g << occurs(s) << '\n';
else
if (act == 3) g << prefix(s) << '\n';
}
f.close();
g.close();
return 0;
}