Cod sursa(job #930151)

Utilizator dragangabrielDragan Andrei Gabriel dragangabriel Data 27 martie 2013 14:31:58
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<string>
#include<climits>
#define chr(a) a-'a'
#define nmax 500005
using namespace std;
vector<int>v[nmax];
int x,y,trie[nmax],fin[nmax],n,i,j,k,rez;
char c[nmax],s[25];

void inc(int x,int poz,int val)
{
	if (!s[poz]) 
		{
			fin[x]+=val;
			return;
	}
	k++;
	v[x].push_back(k);
	c[k]=s[poz];
	trie[k]+=val;
	inc(k,poz+1,val);
}

void add(int x,int poz,int val)
{
	bool ok=false;
	trie[x]+=val;
	c[x]=s[poz];
	if (!s[poz+1]) { fin[x]+=val;return;}
	for (int j=0;j<v[x].size();j++)
		if (c[v[x][j]]==s[poz+1])
		{
			ok=true;
			add(v[x][j],poz+1,val);
		}
		if (!ok)
		{
			inc(x,poz+1,val);
			return;
		}
}

void query(int x,int poz)
{
	if (!s[poz+1]) 
	{
		rez=fin[x];
		return;}
	for (int j=0;j<v[x].size();j++)
		if (c[v[x][j]]==s[poz+1])
			query(v[x][j],poz+1);
}

void prefix(int x,int poz)
{
	if (!trie[x]) return;else
		rez++;
	if (!s[poz+1])	return;		
	for (int j=0;j<v[x].size();j++)
			if (c[v[x][j]]==s[poz+1])
				prefix(v[x][j],poz+1);
}

int main()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	k=chr('z');
	while (gets(s))
	{
		if (s[0]=='0')
			add(chr(s[2]),2,1);else
				if (s[0]=='1')
					add(chr(s[2]),2,-1);else
						if (s[0]=='2')
							rez=0,query(chr(s[2]),2),printf("%d\n",rez);else
								rez=0,prefix(chr(s[2]),2),printf("%d\n",rez);
	}
	return 0;
}