-
Notifications
You must be signed in to change notification settings - Fork 3
/
kth-smallest-or-subarray.cpp
106 lines (86 loc) · 2.16 KB
/
kth-smallest-or-subarray.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
// CPP program to find k-th smallest sum
#include "algorithm"
#include "iostream"
#include "vector"
using namespace std;
int CalculateRank(vector<int> prefix, int n, int x) {
// Initially rank is 0.
int rank = 0;
int sumBeforeIthindex = 0;
for (int i = 0; i < n; ++i) {
// Calculating the count the subarray with
// starting at ith index
int cnt = upper_bound(prefix.begin(), prefix.end(), sumBeforeIthindex + x) -
prefix.begin();
// Subtracting the subarrays before ith index.
cnt -= i;
// Adding the count to rank.
rank += cnt;
sumBeforeIthindex = prefix[i];
}
return rank;
}
int findKthSmallestSum(int a[], int n, int k) {
// PrefixSum array.
vector<int> prefix;
// Total Sum initially 0.
int sum = 0;
for (int i = 0; i < n; ++i) {
sum |= a[i];
prefix.push_back(sum);
}
// Binary search on possible
// range i.e [0, total sum]
int ans = 0;
int start = 0, end = sum;
while (start <= end) {
int mid = (start + end) >> 1;
// Calculating rank of the mid and
// comparing with K
if (CalculateRank(prefix, n, mid) >= k) {
// If greater or equal store the answer
ans = mid;
end = mid - 1;
} else {
start = mid + 1;
}
}
return ans;
}
int naive(int a[], int n, int k) {
vector<int> b;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int val = 0;
for (int k = i; k <= j; ++k) {
std::cout << a[k] << '\t';
val |= a[k];
}
if (i <= j) {
for (int m = 0; m < n - j + i; m++) {
std::cout << '\t';
}
std::cout << '-' << '\t' << val << '\n';
b.push_back(val);
}
}
}
std::cout << '\n';
for (int i = 0; i < (int)b.size(); ++i) {
std::cout << b[i] << '\t';
}
std::cout << '\n';
sort(b.begin(), b.end());
return b[k - 1];
}
int main() {
int a[] = {1, 2, 3};
int k = 6;
int n = sizeof(a) / sizeof(a[0]);
std::cout << "Naive algorithm" << std::endl;
int res = naive(a, n, k);
std::cout << "Last element:" << res << std::endl;
std::cout << "Optimized algorithm" << std::endl;
cout << findKthSmallestSum(a, n, k);
return 0;
}