Pagini recente » Cod sursa (job #2393829) | Cod sursa (job #2177235) | Cod sursa (job #1929909) | Cod sursa (job #1901145) | Cod sursa (job #2035257)
#include <fstream>
std::ifstream fin ("cautbin.in");
std::ofstream fout("cautbin.out");
int a[100001], n, v, M, x;
int BinarySearch_type0(int l, int r, int v); // type 0 means the greatest position with the value equal to v
int BinarySearch_type1(int l, int r, int v); // type 1 means the greatest position with the value lower or equal to v
int BinarySearch_type2(int l, int r, int v); // type 2 means the lowest position with the value greater or equal to v
void Read();
int main()
{
Read();
while (M--)
{
fin >> x >> v;
if (x == 0)
fout << BinarySearch_type0(1, n, v) << '\n';
if (x == 1)
fout << BinarySearch_type1(1, n, v) << '\n';
if (x == 2)
fout << BinarySearch_type2(1, n, v) << '\n';
}
fin.close();
fout.close();
return 0;
}
void Read()
{
fin >> n;
for (int i = 1; i <= n; ++i)
fin >> a[i];
fin >> M;
}
int BinarySearch_type0(int l, int r, int v)
{
int m, poz{-1};
while (l <= r)
{
m = (l + r) / 2;
if (a[m] <= v)
l = m + 1;
else
r = m - 1;
if (a[m] == v)
poz = m;
}
return poz;
}
int BinarySearch_type1(int l, int r, int v)
{
int m, poz{-1};
while (l <= r)
{
m = (l + r) / 2;
if (a[m] <= v)
l = m + 1, poz = m;
else
r = m - 1;
}
return poz;
}
int BinarySearch_type2(int l, int r, int v)
{
int m, poz{-1};
while (l <= r)
{
m = (l + r) / 2;
if (a[m] >= v)
r = m - 1, poz = m;
else
l = m + 1;
}
return poz;
}