Pagini recente » Istoria paginii runda/azidela18simularea/clasament | Cod sursa (job #3204943) | Cod sursa (job #2788664) | Cod sursa (job #2487264) | Cod sursa (job #1107679)
#include <fstream>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <climits>
using namespace std;
#define LEVELS 6
ifstream fin ("hashuri.in");
ofstream fout ("hashuri.out");
int N;
typedef struct nod {
int key;
int value;
struct nod **forward;
} nod;
typedef struct skiplist {
int level;
int size;
struct nod *start;
} skiplist;
skiplist* skiplist_init(skiplist *list) {
nod * header = new nod;
list -> start = header;
header -> key = INT_MAX;
header -> forward = (nod **) malloc(sizeof(nod*) * (LEVELS + 1));
for(int i = 0; i <= LEVELS; ++i)
header -> forward[i] = list -> start;
list->level = 1;
list->size = 0;
return list;
}
int rand_level() {
int level = 1;
while(level < LEVELS && rand() < RAND_MAX / 2)
level++;
return level;
}
void skiplist_insert(skiplist *list, int key) {
nod *update[LEVELS + 1];
nod *x = list -> start;
for(int i = list -> level ; i >= 1 ; --i) {
while(x -> forward[i] -> key < key) {
x = x -> forward[i];
}
update[i] = x;
}
x = x -> forward[1];
int level = rand_level();
if(level > list -> level) {
for(int i = list -> level + 1; i <= level; ++i)
update[i] = list -> start;
list -> level = level;
}
x = (nod*)malloc(sizeof(nod));
x -> key = key;
x -> forward = (nod**) malloc(sizeof(nod*) * (level + 1));
for(int i = 1; i <= level; ++i) {
x -> forward[i] = update[i] -> forward[i];
update[i] -> forward[i] = x;
}
}
nod* skiplist_search(skiplist *list, int key) {
nod *x = list -> start;
for(int i = list -> level; i >= 1; --i) {
while(x -> forward[i] -> key < key)
x = x -> forward[i];
}
x = x -> forward[1];
if(x -> key == key)
return x;
return NULL;
}
nod* skiplist_delete(skiplist *list, int key) {
nod* x = list -> start;
nod* update[LEVELS + 1];
for(int i = list -> level; i >= 1; --i) {
while(x -> forward[i] -> key < key)
x = x -> forward[i];
update[i] = x;
}
x = x -> forward[1];
for(int i = list -> level; i >= 1; --i) {
if(update[i] -> forward[i] -> key == key) {
nod * to_delete = update[i] -> forward[i];
update[i] -> forward[i] = update[i] -> forward[i] -> forward[i];
free(to_delete -> forward);
free(to_delete);
//delete to_delete;
//break;
}
}
x = list -> start;
while(list -> level > 1 && x -> forward[list -> level] -> key == INT_MAX)
list->level--;
}
int main() {
skiplist lis;
skiplist_init(&lis);
fin >> N;
for(int i = 1; i <= N; ++i) {
int type; int value;
fin >> type >> value;
if(type == 1) skiplist_insert(&lis, value);
if(type == 2) skiplist_delete(&lis, value);
if(type == 3) {
nod *p = skiplist_search(&lis, value);
fout << (p != NULL) <<'\n';
}
}
return 0;
}