Cod sursa(job #3188268)
Utilizator | Data | 2 ianuarie 2024 15:40:22 | |
---|---|---|---|
Problema | Cautare binara | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 1.52 kb |
#include <iostream>
#include <fstream>
using namespace std;
int v[100000];
int main()
{
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n,i,m,x,j,intrebare,ok,s,d,mij,poz,poz1,poz2;
fin>>n;
for (i=0; i<n; i++) {
fin>>v[i];
}
fin>>m;
for (j=0; j<m; j++) {
fin>>intrebare>>x;
s=0;
d=n-1;
ok=0;
poz1=s;
poz2=d;
while (s<d-1 && ok==0) {
mij=(s+d)/2;
if (v[mij]>x) {
d=mij;
poz2=d;
}
if (v[mij]<x) {
s=mij;
poz1=s;
}
if (v[mij]==x) {
ok=1;
poz=mij;
poz1=mij;
poz2=mij;
}
}
if (intrebare==0) {
if (ok==0) {
poz=-1;
}
else {
while (v[poz]==x) {
poz++;
}
}
fout<<poz<<endl;
}
if (intrebare==1) {
while (v[poz1]==x) {
poz1++;
}
fout<<poz1<<endl;
}
if (intrebare==2) {
while (v[poz2]==x) {
poz2--;
}
if (ok==1) {
poz2+=2;
}
fout<<poz2<<endl;
}
}
fin.close();
fout.close();
return 0;
}