Pagini recente » Cod sursa (job #2567394) | Cod sursa (job #416450) | Cod sursa (job #1068383) | Cod sursa (job #53506) | Cod sursa (job #2756383)
#include <fstream>
#include <iostream>
using namespace std;
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int binary_search(int n, int arr[100001], int target_value) {
int left = 1, right = n;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target_value) {
return mid;
} else if (arr[mid] > target_value) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
int main() {
int length, arr[100001] = { 0 };
fin >> length;
for (int i = 1; i <= length; ++i) {
fin >> arr[i];
}
int nr_questions, question_type, target_value;
fin >> nr_questions;
while (nr_questions--) {
fin >> question_type >> target_value;
int pos = binary_search(length, arr, target_value);
if (question_type == 2) {
if (pos == -1) {
int smallest_position = 1;
for (int i = 1; i <= length; ++i) {
if (arr[i] > target_value) {
smallest_position = i;
break;
}
}
fout << smallest_position << '\n';
continue;
} else {
int i = pos;
for (i = pos - 1; i >= 1; --i) {
if (arr[i] != target_value) {
break;
}
}
fout << i + 1 << '\n';
continue;
}
} else {
if (pos == -1) {
if (question_type == 0) {
fout << pos << '\n';
continue;
} else {
int i = 1;
for (i = 2; i <= length; ++i) {
if (arr[i] > target_value) {
break;
}
}
fout << i - 1 << '\n';
continue;
}
} else {
int i = pos;
for (i = pos + 1; i <= length; ++i) {
if (arr[i] != target_value) {
break;
}
}
fout << i - 1 << '\n';
continue;
}
}
}
return 0;
}