Pagini recente » Cod sursa (job #2556301) | Cod sursa (job #2024218) | Cod sursa (job #1397387) | Cod sursa (job #2856037) | Cod sursa (job #3170520)
#include <iostream>
#include <fstream>
#include <array>
#define Vec std::array<int, 150000>
int get_first_power(int pos) {
int result = 1;
while (result < pos)
result <<= 1;
if (result == pos) return result;
return (result >> 1);
}
int get_second_power(int pos) {
int result = 1;
while (result < pos)
result <<= 1;
return result;
}
int binary_search_vec_1(const Vec& vec, int n, int x) {
int pos = get_first_power(n - 1);
int pos_final = 0;
while (pos) {
if (vec[pos + pos_final] <= x)
pos_final += pos;
pos >>= 1;
}
if (vec[pos_final] == x) return pos_final;
return -1;
}
int binary_search_vec_2(const Vec& vec, int n, int x) {
int pos = get_first_power(n - 1);
int pos_final = 0;
while (pos) {
if (vec[pos + pos_final] <= x)
pos_final += pos;
pos >>= 1;
}
if (vec[pos_final] <= x) return pos_final;
return -1;
}
int binary_search_vec_3(const Vec& vec, int n, int x) {
int pos = get_second_power(n - 1);
int pos_final = pos;
pos >>= 1;
while (pos) {
if (vec[pos_final - pos] >= x)
pos_final -= pos;
pos >>= 1;
}
if (vec[pos_final] >= x) return pos_final;
return -1;
}
int intrebare_1(const Vec& vec, int n, int x) {
int pos = binary_search_vec_1(vec, n, x);
return pos;
}
int intrebare_2(const Vec& vec, int n, int x) {
int pos = binary_search_vec_2(vec, n, x);
return pos;
}
int intrebare_3(const Vec& vec, int n, int x) {
int pos = binary_search_vec_3(vec, n, x);
return pos;
}
int main()
{
std::ifstream fin("cautbin.in");
std::ofstream fout("cautbin.out");
Vec vec = {-1};
int n, m;
fin >> n;
for (int i = 0; i < n; i++) {
fin >> vec[i];
}
fin>>m;
int command;
int x;
for (int i = 0; i < m; i++) {
fin >> command >> x;
int result;
switch (command) {
case 0:
result = intrebare_1(vec, n ,x);
if (result == -1) {
fout << -1 << "\n";
break;
}
fout << result + 1 << "\n";
break;
case 1:
result = intrebare_2(vec, n, x) + 1;
fout << result << "\n";
break;
case 2:
result = intrebare_3(vec, n, x) + 1;
fout << result << "\n";
break;
}
}
}