-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChandraguptaBST.cpp
executable file
·98 lines (97 loc) · 1.55 KB
/
ChandraguptaBST.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
/* Written By Manav Aggarwal */
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define ll long long
#define MAX 300010
ll MOD = 1e9 + 7;
struct node
{
mutable bool left, right;
ll key;
mutable ll position, index;
bool operator < (node other) const
{
return key < other.key;
}
};
set<node> vals;
ll arr[MAX];
void insrt(node k)
{
ll num;
if(k.index == 0)
{
k.position = 1;
num = 1;
vals.insert(k);
}
else
{
vals.insert(k);
auto it = vals.find(k);
auto it1 = it; it1++;
if(it == vals.begin())
{
it++;
if(!(it -> left))
{
it -> left = true;
num = ((it -> position)*2);
num %= MOD;
--it;
it -> position = num;
}
}
else if(it1 == vals.end())
{
it1--; it1--;
if(!(it1->right))
{
it1 -> right = true;
num = (it1 -> position)*2 + 1;
num %= MOD;
++it1;
it1 -> position = num;
}
}
else
{
it--;
if(!(it -> right))
{
it -> right = true;
num = (it -> position)*2 + 1;
num %= MOD;
++it;
it -> position = num;
}
else if(!(it1 -> left))
{
it1 -> left = true;
num = (it1 -> position)*2;
num %= MOD;
--it1;
it1 -> position = num;
}
}
}
arr[k.index] = num % MOD;
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
ll n, i, num;
cin >> n;
for(i = 0; i < n; i++)
{
node k;
cin >> k.key;
k.left = k.right = false;
k.index = i;
insrt(k);
num = arr[i] % MOD;
cout << num << " ";
}
return 0;
}