Cod sursa(job #589614)

Utilizator Magnuscont cu nume gresit sau fals Magnus Data 12 mai 2011 22:22:38
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <cstdio>
#include <cstring>

using namespace std;

struct trie
{
	int cnt,ns;
    trie *son[26];
	trie()
    {
		cnt=0;
		ns=0;
		memset(son,0,sizeof(son));
	}
};

trie *t=new trie;

void ins(trie *node,char *ch)
{
	if(*ch=='\n')
	{
        node->cnt++;
        return;
	}
	if( node->son[*ch-'a']==0)
	{
		node->son[*ch-'a']=new trie;
		node->ns++;
	}
	ins(node->son[*ch-'a'],ch+1);
}

int del(trie *node,char *ch)
{
	if(*ch=='\n')
		node->cnt--;
	else if (del(node->son[*ch-'a'],ch+1))
	{
        node->son[*ch-'a']=0;
        node->ns--;
    }
	if(node->cnt==0&&node->ns==0&&node!=t)
	{
		delete node;
		return 1;
	}
	return 0;
}

int query(trie*node,char *ch)
{
	if(*ch =='\n')
		return node->cnt;
	if(node->son[*ch-'a'])
		return query(node->son[*ch-'a'],ch+1);
	return 0;
}

int prefix(trie*node,char *ch,int k)
{
	if(*ch=='\n'||node->son[*ch-'a']==0)
		return k;
	return prefix(node->son[*ch-'a'],ch+1,k+1);
}

int main()
{
	char v[32];
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	fgets(v,32,stdin);
	while(!feof(stdin))
	{
        if (v[0]=='0') ins(t,v+2);
        else if (v[0]=='1') del(t,v+2);
        else if (v[0]=='2') printf("%d\n",query(t,v+2));
        else printf( "%d\n",prefix(t,v+2,0));
        fgets(v,32,stdin);
	}
	return 0;
}