Skip to content

Commit 0b668c3

Browse files
add (solution) : interactive-search (#462)
Problem Lin : https://lightoj.com/problem/interactive-search
1 parent 5d98a65 commit 0b668c3

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

interactive-search/en.md

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# Interactive Search
2+
3+
## Problem
4+
This is an easy interactive problem . You will be a value `n` and you have to find the secret number which is within `1` to `n` in `30` tries . You will be given a response `high` or `low` or `correct` . If you guess the number in `30` tries you will get `AC` otherwise `WA` .
5+
6+
## Solution
7+
8+
The maximum value of `n` is `1e9` so we can't use linear search .
9+
10+
As the number of tries is `30` we can use binary search to find the number because to find a number within a range of `1` to `1e9` it will take binary search maximum `log2(1e9)` which is okay for our problem.
11+
12+
13+
So we will use binary search to find the number .
14+
```
15+
1. We will take the input of `n` and set the `low` as `1` and `high` as `n`.
16+
2. Then we will find the mid value and print it as guess .
17+
3. Then we will take the response as input .
18+
5. If the response is `high` then we will set `high` as `mid - 1` .
19+
6. If the response is `low` then we will set `low` as `mid + 1` .
20+
7. If the response is `correct` then we will return .
21+
8. If the count is greater than `30` then we will print `too many tries` and return .
22+
```
23+
24+
You can learn more about binary search from
25+
1. [geeksforgeeks](https://www.geeksforgeeks.org/binary-search/)
26+
2. [cp-algorithms](https://cp-algorithms.com/num_methods/binary_search.html)
27+
28+
```
29+
Time Complexity : O(log(n))
30+
Space Complexity : O(1)
31+
```
32+
33+
34+
35+
36+
## CPP
37+
```cpp
38+
39+
#include <bits/stdc++.h>
40+
41+
using namespace std;
42+
43+
int main()
44+
{
45+
46+
int low = 1, high = 100000;
47+
// Taking the value of n as input and setting it as high as it will be the maximum value
48+
cin >> high;
49+
50+
51+
// To keep track of the number of tries
52+
int count = 0;
53+
54+
// Binary search
55+
while (low <= high)
56+
{
57+
// Finding the mid value
58+
int mid = (low + high) >> 1;
59+
// Printing the guess
60+
cout << "guess " << mid << endl;
61+
62+
63+
// Taking the response as input
64+
string response;
65+
cin >> response;
66+
67+
// Checking the response
68+
if (response == "correct")
69+
return 0;
70+
else if (response == "high")
71+
high = mid - 1;
72+
else if (response == "low")
73+
low = mid + 1;
74+
75+
// Increasing the count
76+
count++;
77+
78+
// If the count is greater than 30 then printing too many tries and returning
79+
if (count >= 30)
80+
{
81+
cout << "too many tries" << endl;
82+
return 0;
83+
}
84+
}
85+
86+
return 0;
87+
}
88+
```

0 commit comments

Comments
 (0)