Pagini recente » Cod sursa (job #229902) | Cod sursa (job #237707)
Cod sursa(job #237707)
#include <stdio.h>
#include <algorithm>
using namespace std;
struct trie
{
int nrc, cnt;
trie *fii[26];
trie()
{
memset(fii, 0, sizeof(fii));
cnt = nrc = 0;
}
} *rad_ti = new trie;
int oper;
char str[32];
void insert_ti(trie *nod, char s[])
{
if (s[0] == '\n')
{
nod->cnt++;
return;
}
if (nod->fii[s[0] - 'a'] == 0)
{
nod->nrc++;
nod->fii[s[0] - 'a'] = new trie;
}
insert_ti(nod->fii[s[0] - 'a'], s + 1);
}
bool delete_ti(trie *nod, char s[])
{
if (s[0] == '\n')
nod->cnt--;
else if (delete_ti(nod->fii[s[0] - 'a'], s + 1))
{
nod->nrc--;
nod->fii[s[0] - 'a'] = 0;
}
if (!nod->cnt && !nod->nrc && nod != rad_ti)
{
delete(nod);
return 1;
}
return 0;
}
int cauta_ti(trie *nod, char s[])
{
if (s[0] == '\n')
return nod->cnt;
if (nod->fii[s[0] - 'a'])
return cauta_ti(nod->fii[s[0] - 'a'], s + 1);
return 0;
}
int pref_ti(trie *nod, char s[], int lvl)
{
if (s[0] == '\n')
return lvl;
if (nod->fii[s[0] - 'a'])
return pref_ti(nod->fii[s[0] - 'a'], s + 1, lvl + 1);
return lvl;
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
scanf("%d ", &oper);
fgets(str, 25, stdin);
while (!feof(stdin))
{
if (!oper)
insert_ti(rad_ti, str);
if (oper == 1)
delete_ti(rad_ti, str);
if (oper == 2)
printf("%ld\n", cauta_ti(rad_ti, str));
if (oper == 3)
printf("%ld\n", pref_ti(rad_ti, str, 0));
scanf("%d ", &oper);
fgets(str, 25, stdin);
}
fclose(stdin);
fclose(stdout);
return 0;
}