Cod sursa(job #1313700)

Utilizator whoasdas dasdas who Data 10 ianuarie 2015 23:15:04
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#define IA_PROB "hashuri"

#include <cassert>
#include <cstdio>
#include <cstring>

#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>

#include <algorithm>

using namespace std;

template <typename T, int MAX_HEIGHT>
class SkipList {
private:
	struct Node {
		T key;
		int height;
		Node *next[];
	private:
		Node();
	} *head;
	int cur_lvl;

	Node *last[MAX_HEIGHT];
	void reset_last() {
		for (int lvl = cur_lvl + 1; lvl < MAX_HEIGHT; lvl++)
			last[lvl] = head;
	}
	Node *find_llt(T x) {
		reset_last();
		Node *i = head;
		for (int lvl = cur_lvl; lvl >= 0; lvl--) {
			while (i->next[lvl] && i->next[lvl]->key < x) {
				i = i->next[lvl];
			}
			last[lvl] = i;
		}
		return i;
	}
	int get_rand_height() {
		return rand() % MAX_HEIGHT;
	}
public:
	SkipList() : cur_lvl(0) {
		head = (Node*)malloc(sizeof(Node) + sizeof(Node*) * MAX_HEIGHT);
		memset(head->next, 0, sizeof(Node*) * MAX_HEIGHT);
		head->key = 1234;
		head->height = MAX_HEIGHT - 1;
	}
	bool find(T x) {
		Node *found = find_llt(x);
		return found->next[0] && found->next[0]->key == x;
	}
	void insert(T x) {
		if (!find(x)) {
			assert(!last[0]->next[0] || last[0]->next[0]->key > x);

			int height = get_rand_height();
			Node *node = (Node*)malloc(sizeof(Node) + sizeof(Node*) * (height + 1));
			node->height = height;
			node->key = x;

			cur_lvl = max(cur_lvl, height);
			for (int lvl = 0; lvl <= height; lvl++) {
				node->next[lvl] = last[lvl]->next[lvl];
				last[lvl]->next[lvl] = node;
			}
		}
	}
	void remove(T x) {
		if (find(x)) {
			Node *found = last[0]->next[0];
			assert(found->key == x);
			for (int lvl = 0; lvl <= found->height; lvl++) {
				assert(last[lvl] == head || last[lvl]->key < found->key);
				last[lvl]->next[lvl] = found->next[lvl];
			}
			free(found);
		}
		while (head->next[cur_lvl] == NULL) {
			cur_lvl--;
		}
	}
};


int main()
{
	freopen(IA_PROB".in", "r", stdin);
	freopen(IA_PROB".out", "w", stdout);

	SkipList<int, 16> skip_list;

	int n;
	scanf("%d", &n);
	while ( n --> 0) {
		int op, x;
		scanf("%d %d", &op, &x);
		switch (op) {
		case 1: skip_list.insert(x); break;
		case 2: skip_list.remove(x); break;
		case 3: printf("%d\n", (int)skip_list.find(x)); break;
		default: exit(1);
		}
	}

	return 0;
}