Cod sursa(job #2384976)
Utilizator | Data | 21 martie 2019 13:12:25 | |
---|---|---|---|
Problema | Cautare binara | Scor | 0 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.37 kb |
using namespace std;
#include<iostream>
#include<fstream>
int main() {
ifstream fin("cautbin.in");
ofstream fout("cautbin.out");
int n;
fin >> n;
int v[n+1];
for (int i = 1; i<=n; i++) {
fin >> v[i];
}
int m;
fin >> m;
struct pereche {
int c;
int x;
};
pereche a[m+1];
for (int i = 1; i<=m; i++) {
fin >> a[i].c;
fin >> a[i].x;
}
for (int i = 1; i<=m; i++) {
if (a[i].c == 0) {
int st = 1;
int dr = n;
int ok = 0;
while (st < dr) {
int mid = (st+dr)/2;
if (v[mid] > a[i].x) {
dr = mid-1;
} else if (v[mid] < a[i].x) {
st = mid+1;
} else {
if (v[mid+1] == a[i].x) {
while (v[mid+1] == a[i].x) {
mid++;
}
fout << mid << endl;
ok = 1;
break;
} else {
fout << mid << endl;
ok = 1;
break;
}
}
}
if (ok == 0) {
fout << "-1" << endl;
}
} else if (a[i].c == 1) {
int st = 1;
int dr = n;
while (st < dr) {
int mid = (st+dr)/2;
if (v[mid] > a[i].x) {
dr = mid-1;
} else {
while (v[mid+1] <=a[i].x) {
mid++;
}
fout << mid << endl;
break;
}
}
} else if (a[i].c == 2) {
int st = 1;
int dr = n;
while (st < dr) {
int mid = (st+dr)/2;
if (v[mid] < a[i].x) {
st = mid+1;
} else {
while (v[mid-1] >= a[i].x) {
mid--;
}
fout << mid << endl;
break;
}
}
}
}
fin.close();
fout.close();
return 0;
}