-
Notifications
You must be signed in to change notification settings - Fork 2
/
discrete binary_search.cpp
93 lines (81 loc) · 1.48 KB
/
discrete binary_search.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
//binary search
//topcoder
//discrete
// like lower_bound and upper_bound
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<ctype.h>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<math.h>
using namespace std;
#define inf 1000000000
#define mod 1000000007
#define ll long long
#define in(x) scanf("%d",&x);
#define rep(i,n) for(i=0;i<n;i++)
#define rrep(i,n) for(i=n-1;i>=0;i--)
#define pii pair<int,int>
#define vi vector<int>
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
const double pi(3.14159265358979);
int check(int x)
{
if (x<=2)
return 1;
else
return 0;
}
// consider arr as 111111000000
// finds last element which is 1
// if there is no 1 b/w l and r, (least possible value of l) - 1 is returned
int bs1()
{
int l=3, r=100000;
while(l<r)
{
int mid = (l+r+1)>>1;
if(check(mid))
l=mid;
else
r=mid-1;
}
if(check(l))
return l;
else
return l-1;
}
// finds element with first 0
// if there is no 0 b/w l and r, (highest possible r) + 1 is returned
int bs0()
{
int l=0,r=100000;
while(l<r)
{
int mid = (l+r)>>1;
if(check(mid))
l=mid+1;
else
r=mid;
}
if(check(r)==0)
return r;
else
return r+1;
}
int main()
{
int x = bs1();
cout<<x<<endl;
x = bs0();
cout<<x<<endl;
return 0;
}