Pagini recente » Cod sursa (job #2768342) | Cod sursa (job #517755) | Cod sursa (job #1047199) | Cod sursa (job #3153799) | Cod sursa (job #2908382)
#include <fstream>
using namespace std;
const int N = 1e5;
const int L = 16;
int v[N+1], n;
int caut_1(int x)
{
///cauta cel mai mare rez cu v[rez] <= x
int rez = 0, pas = 1 << L;
while (pas != 0)
{
if (rez + pas <= n && v[rez+pas] <= x)
{
rez += pas;
}
pas /= 2;
}
return rez;
}
int caut_0(int x)
{
int rez = caut_1(x);
if (rez > 0 && v[rez] == x)
{
return rez;
}
return -1;
}
int caut_2(int x)
{
///cauta cel mai mic rez cu v[rez] >= x
///intr-o prima faza vom cauta cel mai mare rez cu v[rez] < x
int rez = 0, pas = 1 << L;
while (pas != 0)
{
if (rez + pas <= n && v[rez+pas] < x)
{
rez += pas;
}
pas /= 2;
}
rez++;///cea mai mica pozitie pe care se afla ceva >= x este
///(cea mai mare pozitie pe care se afla ceva mai < x) + 1
return rez;
}
int main()
{
ifstream in("cautbin.in");
ofstream out("cautbin.out");
in >> n;
for (int i = 1; i <= n; i++)
{
in >> v[i];
}
int nq;
in >> nq;
for (int i = 0; i < nq; i++)
{
int tip, val;
in >> tip >> val;
if (tip == 0)
{
out << caut_0(val);
}
else if (tip == 1)
{
out << caut_1(val);
}
else
{
out << caut_2(val);
}
out << "\n";
}
in.close();
out.close();
return 0;
}