Cod sursa(job #236968)

Utilizator hadesgamesTache Alexandru hadesgames Data 28 decembrie 2008 20:27:04
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <algorithm>
#include <utility>
#include <string>
#include <functional>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
#define FOR(i,a,b) for (i=a;i<=b;i++)
#define fori(it,v) for (it=(v).begin();it!=(v).end();it++)
#define pb push_back
#define mp make_pair
#define fs first
#define ss second
#define all(c) c.begin(),c.end()
#define pf push_front
#define popb pop_back
#define popf pop_front
struct nod
{
	int nr,nrf;
	nod *v[26];
	nod() 
	{
		nr = nrf = 0;
		memset(v,0,sizeof(v));
	}
};
nod *trie=new nod;
void add(char *s,nod * y)
{
	int i;
	if (*s=='\0')
	{
		y->nr++;
		return;
	}
	if (y->v[*s-'a']==NULL)
		y->v[*s-'a']=new nod;
	y->nrf++;
	add(s+1,y->v[*s-'a']);
}
int del(char *s,nod * y)
{
	if (*s=='\0')
	{
		y->nr--;
		if (y->nr==0)
		{
			delete y;
			return 1;
		}
		return 0;
	}
	y->nrf--;
	if (del(s+1,y->v[*s-'a']))
		y->v[*s-'a']=NULL;
	if (y->nrf==0&&y->nr==0)
	{
		delete y;
		return 1;
	}
	return 0;
}
int nr(char *s,nod * y)
{
	if (*s=='\0')
		return y->nr;
	if (y->v[*s-'a']==NULL)
		return 0;
	return nr(s+1,y->v[*s-'a']);
}
int prefix(char *s,nod*y)
{	
	if (*s=='\0')
		return 0;
	if (y->v[*s-'a']==NULL)
		return 0;
	return 1+prefix(s+1,y->v[*s-'a']);
}
char s[40];
int w;
int main()
{
	FILE *in,*out;
	in=fopen("trie.in","r");
	out=fopen("trie.out","w");
	while (fscanf(in,"%d %s\n",&w,s)!=EOF)
	{
		if (w==0)
			add(s,trie);
		if (w==1)
			del(s,trie);
		if (w==2)
			fprintf(out,"%d\n",nr(s,trie));
		if (w==3)
			fprintf(out,"%d\n",prefix(s,trie));
	}
}