forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Skip-List.cpp
130 lines (120 loc) · 1.7 KB
/
Skip-List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <cstdio>
#include <cstdlib>
#define NIL 0
#define LAYER_COUNT 20
#define NODE_COUNT 100000
using namespace std;
struct node
{
int id, value;
node *next, *lower;
node();
};
node::node() : next(NIL) { }
node *head[LAYER_COUNT];
void init()
{
head[0] = new node;
for (int i = 1; i < LAYER_COUNT; i++)
{
head[i] = new node;
head[i]->lower = head[i - 1];
}
}
void insert(int id, int value)
{
int k = 0;
while ((rand() & 1) == 0)
{
k++;
}
node *prev = head[k], *cur = head[k], *upper = NIL;
for (; k >= 0; k--)
{
while (cur != NIL && cur->id < id)
{
prev = cur;
cur = cur->next;
}
node *o = new node;
o->next = cur;
o->id = id;
o->value = value;
prev->next = o;
prev = prev->lower;
cur = prev;
if (upper != NIL)
{
upper->lower = o;
}
upper = o;
}
}
int find(int id)
{
node *prev, *cur = head[LAYER_COUNT - 1];
for (int k = LAYER_COUNT - 1; k >= 0; k--)
{
while (cur != NIL && cur->id < id)
{
prev = cur;
cur = cur->next;
}
if (cur != NIL && cur->id == id)
{
return cur->value;
}
else
{
prev = prev->lower;
cur = prev;
}
}
return -1;
}
void debug()
{
for (int i = 5; i >= 0; i--)
{
node *cur = head[i];
printf("head[%d]", i);
while (cur != NIL)
{
printf(" -> (%d, %d)", cur->id, cur->value);
cur = cur->next;
}
printf("\n");
}
}
int main()
{
int in, id, value;
init();
while (true)
{
scanf("%d", &in);
if (in == 1)
{
scanf("%d%d", &id, &value);
insert(id, value);
}
else if (in == 2)
{
scanf("%d", &id);
printf("%d\n", find(id));
}
else if (in == 4)
{
debug();
}
else if (in == 0)
{
return 0;
}
else
{
printf("No such command!\n");
}
}
return 0;
}