Cod sursa(job #1942553)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 28 martie 2017 01:42:07
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
#define MaxN 2000005
#define INF 2140000000
using namespace std;
  
FILE*IN,*OUT;

int Type,Ans,alpha=1,Size=0;
char wrd[20];
struct Trie
{
	unsigned short fr,final;
	int	sons[26];
}T[MaxN];
void Add(char w[])
{
	int node=0,next;
	for(int i=0;w[i]!=0;i++)
	{
		next=T[node].sons[w[i]-'a'];
		if(next==0)
		{
			next=++Size;
			T[node].sons[w[i]-'a']=next;
			T[next].fr++;
		}
		else T[next].fr++;
		node=next;
	}
	T[node].final++;
}
void Delete(char w[])
{
	int node=0,next;
	for(int i=0;w[i]!=0;i++)
	{
		next=T[node].sons[w[i]-'a'];
		T[next].fr--;
		node=next;
	}
	T[node].final--;
}
int Common(char w[])
{
	int node=0,next,i;
	for(i=0;w[i]!=0;i++)
	{
		next=T[node].sons[w[i]-'a'];
		if(T[next].fr>0)node=next;
		else return i;
	}
	return i;
}
int Frequency(char w[])
{
	int node=0,next;
	for(int i=0;w[i]!=0;i++)
	{
		next=T[node].sons[w[i]-'a'];
		if(T[next].fr==0)return 0;
		node=next;
	}
	return T[node].final;
}
int main()
{
    IN=fopen("trie.in","r");
    OUT=fopen("trie.out","w");
	
	while(fscanf(IN,"%d %s",&Type,wrd)!=-1)
	{
		if(Type==0)
			Add(wrd);
		else if(Type==1)
			Delete(wrd);
		else if(Type==2)
			fprintf(OUT,"%d\n",Frequency(wrd)),alpha++;
		else if(Type==3)
			fprintf(OUT,"%d\n",Common(wrd)),alpha++;
		memset(wrd,0,sizeof wrd);
	}
	return 0;
}