Pagini recente » Cod sursa (job #315370) | Cod sursa (job #754897) | Cod sursa (job #324776) | Cod sursa (job #311383) | Cod sursa (job #754812)
Cod sursa(job #754812)
#include <cstdio>
#include <cstring>
using namespace std;
#define ch (*s - 'a')
struct Trie
{
int cuv, nrfii;
Trie *fiu[31];
Trie()
{
cuv = nrfii = 0;
memset(fiu, 0, sizeof(fiu));
}
};
Trie *T = new Trie;
void Insert(Trie *nod, char *s)
{
if(*s == '\n')
{
nod->cuv++;
return;
}
if(nod->fiu[ch] == 0)
{
nod->fiu[ch] = new Trie;
nod->nrfii++;
}
Insert(nod->fiu[ch], s + 1);
}
int Delete(Trie *nod, char *s)
{
if(*s == '\n')
{
nod->cuv--;
}else
{
if(Delete(nod->fiu[ch], s + 1))
{
nod->fiu[ch] = 0;
nod->nrfii--;
}
}
if(nod->cuv == 0 && nod->nrfii == 0 && nod != T)
{
delete nod;
return 1;
}
return 0;
}
int Count(Trie *nod, char *s)
{
if(*s == '\n') return nod->cuv;
if(nod->fiu[ch] != 0) return Count(nod->fiu[ch], s + 1);
return 0;
}
int Length(Trie *nod, char *s, int k)
{
if(*s == '\n' || nod->fiu[ch] == 0) return k;
return Length(nod->fiu[ch], s + 1, k + 1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
char line[31];
fgets(line, 31, stdin);
while(!feof(stdin))
{
if(line[0] == '0') Insert(T, line + 2);
if(line[0] == '1') Delete(T, line + 2);
if(line[0] == '2') printf("%i\n", Count(T, line + 2));
if(line[0] == '3') printf("%i\n", Length(T, line + 2, 0));
fgets(line, 31, stdin);
}
return 0;
}