Cod sursa(job #569029)

Utilizator antoanelaAntoanela Siminiuc antoanela Data 31 martie 2011 21:49:00
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <cstdio>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#define f first
#define s second

string cuv;
vector <int> trie, triesum;
vector <vector <pair<int, int> > > v;

inline void addTrie(const string &cuv, int val)
{
	string::const_iterator it;
	int i, next, root=0;
	for (it=cuv.begin(); it!=cuv.end(); it++)
	{
		next=-1;
		for (i=0; i<v[root].size(); i++)
			if (v[root][i].f==*it)
				next=v[root][i].s;
		if (next==-1)
		{
			next=trie.size();
			trie.push_back(0);
			triesum.resize(trie.size());
			v.resize(trie.size());
			v[root].push_back (make_pair (*it, next));
		}
		triesum[root]+=val;
		root=next;
	}
	trie[root]+=val;
	triesum[root]+=val;
}

inline int countWords(const string &cuv)
{
	string::const_iterator it;
	int i, next, root=0;
	for (it=cuv.begin(); it!=cuv.end(); it++)
	{
		next=-1;
		for (i=0; i<v[root].size(); i++)
			if (v[root][i].f==*it)
				next=v[root][i].s;
		if (next==-1) return 0;
		root=next;
	}
	return trie[root];
}

inline int longestPrefix(const string &cuv)
{
	string::const_iterator it;
	int i, next, root=0, l=0;
	for (it=cuv.begin(); it!=cuv.end(); it++)
	{
		next=-1;
		for (i=0; i<v[root].size(); i++)
			if (v[root][i].f==*it)
				next=v[root][i].s;
		if (next==-1) return l;
		root=next;
		if (!triesum[root]) return l;
		l++;
	}
	return l;
}

int main()
{
	ifstream fin("trie.in");
	freopen("trie.out","w",stdout);
	trie.push_back(0);
	triesum.push_back(0);
	int t;
	string::iterator it;
	v.resize(1);
	for ( ; fin >> t >> cuv;)
	{
		if (!t) addTrie(cuv, 1);
		if (t==1) addTrie(cuv, -1);
		if (t==2) printf("%d\n",countWords(cuv)); 
		if (t==3) printf("%d\n",longestPrefix(cuv));
	}
	return 0;
}