Cod sursa(job #975528)

Utilizator tudorv96Tudor Varan tudorv96 Data 20 iulie 2013 15:22:18
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 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;
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;
				fr[x]++;
				break;
			}
		if (!f) {
			g.push_back(null);
			g[x].push_back(last);
			fr.push_back(1);
			L.push_back(L[x] + 1);
			nod.push_back (s[now]);
			x = last;
		}
		++now;
	}
}	

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

int frecv() {
	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;
				break;
			}
			++now;
	}
	return (!g[x].size() ? fr[x] : 0);
}

int common() {
	int x = 0; now = 0;
	while (now < s.size() && g[x].size()) {
		for (list <int> :: iterator it = g[x].begin(); it != g[x].end(); ++it)
			if (nod[*it] == s[now]) {
				x = *it;
				break;
			}
			++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();
}