Pagini recente » Cod sursa (job #944261) | Cod sursa (job #1864643) | Cod sursa (job #2137424) | Cod sursa (job #154573) | Cod sursa (job #2703535)
#include <fstream>
#include <vector>
using namespace std;
const int N_MAX = 100000;
int n;
int arr[N_MAX];
// returns the first index of a number >= val
int lower_bound(int val) {
int bit = 1;
for (; bit < n; bit <<= 1);
int index = n - 1;
for (; bit; bit >>= 1) {
if (index - bit >= 0 && arr[index - bit] >= val) {
index -= bit;
}
}
if (arr[index] < val) {
index = -1;
}
return index;
}
// returns the last index of a number <= val
int upper_bound(int val) {
int bit = 1;
for (; bit < n; bit <<= 1);
int index = 0;
for (; bit; bit >>= 1) {
if (index + bit < n && arr[index + bit] <= val) {
index += bit;
}
}
if (arr[index] > val) {
index = -1;
}
return index;
}
int main() {
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
fin >> n;
for (int i = 0; i < n; i++) {
fin >> arr[i];
}
int m;
fin >> m;
int op, val, index;
for (int i = 0; i < m; i++) {
fin >> op >> val;
if (op < 2) {
index = upper_bound(val);
if (op == 0 && arr[index] != val) {
index = -1;
}
} else {
index = lower_bound(val);
}
if (index != - 1) {
index++;
}
fout << index << endl;
}
fin.close();
fout.close();
return 0;
}