Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- using namespace std;
- int binary_search (int* a, int l, int r, int k){
- if (r >= l){
- int idx = l + (r - l) / 2;
- if (a[idx] == k){
- return idx;
- }
- if (a[idx] > k) return binary_search(a, l, idx - 1, k);
- return binary_search(a,idx+1,r, k);
- }
- return -1;
- }
- int main() {
- ifstream cin("binsearch.in");
- ofstream cout("binsearch.out");
- int n;
- cin >> n;
- int a[n];
- for (int i = 0; i < n; i++) {
- cin >> a[i];
- }
- int m;
- cin >> m;
- while(m != 0){
- int x;
- cin >> x;
- int pos = binary_search(a,0,n-1,x);
- int mn = pos, mx = pos;
- if (pos == -1) cout << pos << " " << pos << endl;
- else{
- while (pos > 0){
- pos = binary_search(a,0,pos - 1,x);
- if (pos != -1) mn = pos;
- }
- pos = mx;
- while (pos < n - 1 && pos > -1){
- pos = binary_search(a,pos + 1,n - 1,x);
- if (pos != -1) mx = pos;
- }
- cout << mn + 1 << " " << mx + 1 << endl;
- }
- m--;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement