Cod sursa(job #975537)

Utilizator tudorv96Tudor Varan tudorv96 Data 20 iulie 2013 16:00:46
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <string>
#include <list>
#include <vector>
using namespace std;

#define last (int)(g.size()-1)

ifstream fin ("trie.in");
ofstream fout ("trie.out");

vector <list <int> > g;
list <int> null;
vector <char> nod;
vector <int> fr, L, l;
int t; 
string s;
unsigned now;

void insert() {
	int x = 0; now = 0;
	while (now < s.size()) {
		bool f = 0;
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (nod[*it] == s[now]) {
				f = 1;
				x = *it;
				l[*it]++;
				break;
			}
		if (!f) {
			g.push_back(null);
			g[x].push_back(last);
			fr.push_back(0);
			L.push_back(L[x] + 1);
			nod.push_back (s[now]);
			l.push_back(1);
			x = last;
		}
		++now;
	}
	fr[x]++;
}	

void erase() {
	int x = 0; now = 0;
	while (now < s.size()) {
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (nod[*it] == s[now]) {
				x = *it;
				l[x]--;
				break;
			}
			++now;
	}
	fr[x]--;
}

int frecv() {
	int x = 0; now = 0;
	while (now < s.size()) {
		bool f = 0;
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (nod[*it] == s[now]) {
				x = *it;
				f = 1;
				break;
			}
			if (!f)
				return 0;
			++now;
	}
	return fr[x];
}

int common() {
	int x = 0; now = 0;
	while (now < s.size()) {
		bool f = 0;
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (nod[*it] == s[now] && l[*it]) {
				x = *it;
				f = 1;
				break;
			}
			if (!f)
				return L[x];
			++now;
	}
	return L[x];
}

int main() {
	g.push_back(null);
	L.push_back(0);
	fr.push_back(0);
	nod.push_back(0);
	while (fin >> t >> s) {
		if (!t) 
			insert();
		if (t == 1)
			erase();
		if (t == 2)
			fout << frecv() << "\n";
		if (t == 3)
			fout << common() << "\n";
	}
	fcloseall();
}