Cod sursa(job #2290615)

Utilizator marcudanfDaniel Marcu marcudanf Data 26 noiembrie 2018 19:03:14
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

vector < int > trie, s;
vector < vector < pair <int, int > > > m;

int muchie(int root, char c){
	for(auto i : m[root])
		if(i.first == c)
			return i.second;
	return -1;
}

void add(char c[21], int val){
	int root = 0;
	for(int i = 0; c[i]; i++){
		int next = muchie(root, c[i]);
		if(next == -1){
			next = trie.size();
			trie.push_back(0);
			s.resize(trie.size());
			m.resize(trie.size());
			m[root].push_back({c[i], next});
		}
		s[root] += val;
		root = next;
	}
	trie[root] += val;
}

int aparitii(char c[21]){
	int root = 0;
	for(int i = 0; c[i]; i++){
		root = muchie(root, c[i]);
		if(root == -1)
			return -1;
	}
	return trie[root];
}

int common(char c[21]){
	int last = 0, current = 0, root = 0;
	for(int i = 0; c[i]; i++){
		root = muchie(root, c[i]);
		if(root == -1)
			return last;
		current++;
		if(s[root] or trie[root])
			last = current;
	}
	return last;
}


int main(){
	trie.reserve(500000);
	trie.resize(1);
	s.reserve(500000);
	s.resize(1);
	m.reserve(500000);
	m.resize(1);
	int task;
	char c[21];
	while(fin >> task >> c){
		if(!task){
			add(c, 1);
		}else if(task == 1){
			add(c, -1);
		}else if(task == 2){
			fout << aparitii(c) << '\n';
		}else{
			fout << common(c) << '\n';
		}
	}
	return 0;
}