Cod sursa(job #1241326)

Utilizator DenisacheDenis Ehorovici Denisache Data 13 octombrie 2014 11:59:37
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <list>
//#include <windows.h>
//#include <conio.h>
#include <cstdlib>
#include <time.h>
#include <limits.h>
#include <string>
#include <math.h>
using namespace std;
#define forA(V,it) for (typeof(V.begin()) it=V.begin();it!=V.end();it++)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define ull unsigned ll
#define MOD 1000000007
#define INF (1<<31)-1
#define MINF -(1<<31)
#define vi vector <int>
#define vll vector <ll>
#define pii pair <int,int>
#define pll pair <ll,ll>
#define newl printf("\n")
#define DIM 1000000
int N,i;
struct Trie
{
	int cnt,nrsons;
	Trie *son[26];
	Trie()
	{
		cnt=nrsons=0;
		memset(son,0,sizeof(son));
	}
};
Trie *T=new Trie;
void ins(Trie *nod,char *s)
{
	if (*s=='\n')
	{
		nod->cnt++;
		return;
	}
	if (nod->son[*s-'a']==0)
	{
		nod->son[*s-'a']=new Trie;
		nod->nrsons++;
	}
	ins(nod->son[*s-'a'],s+1);
}
int del(Trie *nod,char *s)
{
	if (*s=='\n') nod->cnt--;
	else if (del(nod->son[*s-'a'],s+1))
	{
		nod->son[*s-'a']=0;
		nod->nrsons--;
	}
	if (nod->cnt==0 && nod->nrsons==0 && nod!=T)
	{
		delete nod;
		return 1;
	}
	return 0;
}
int que(Trie *nod,char *s)
{
	if (*s=='\n') return nod->cnt;
	else if (nod->son[*s-'a']) return que(nod->son[*s-'a'],s+1);
	return 0;
}
int pre(Trie *nod,char *s,int k)
{
	if (*s=='\n' || nod->son[*s-'a']==0) return k;
	return pre(nod->son[*s-'a'],s+1,k+1);
}
char cmd[35];
int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    fgets(cmd,32,stdin);
    while (!feof(stdin))
    {
    	if (cmd[0]=='0') ins(T,cmd+2);
    	else if (cmd[0]=='1') del(T,cmd+2);
    	else if (cmd[0]=='2') printf("%d\n",que(T,cmd+2));
    	else printf("%d\n",pre(T,cmd+2,0));
    	fgets(cmd,32,stdin);
    }
    return 0;
}