Pagini recente » Cod sursa (job #205934) | Cod sursa (job #1784246) | Cod sursa (job #1518853) | Cod sursa (job #2053343) | Cod sursa (job #2703532)
#include <fstream>
#include <vector>
using namespace std;
// returns the first index of a number >= val
int lower_bound(int val, vector<int> & arr) {
int n = arr.size();
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, vector<int> & arr) {
int n = arr.size();
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");
int n;
fin >> n;
vector<int> arr(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, arr);
if (op == 0 && arr[index] != val) {
index = -1;
}
} else {
index = lower_bound(val, arr);
}
if (index != - 1) {
index++;
}
fout << index << endl;
}
fin.close();
fout.close();
return 0;
}