题解 | #【模板】二分#
【模板】二分
https://www.nowcoder.com/practice/f06ba3a3008a45e0853f123a28c10836
#include "bits/stdc++.h"
//注意原区间为左闭右开!(我就是因为这个wa了好几发,哭了)
using namespace std;
#define int long long
#define endl "\n"
#define PII pair<int,int>
#define PIII pair<int,PII>
const int MOD = 1e9 + 7;
const int N = 3e5;
void slu() {
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; i++)cin >> a[i];
for (int i = 0; i < m; i++) {
int t;
cin >> t;
if (t == 1) {
int l, r, x;
cin >> l >> r >> x;
auto it = std::lower_bound(a.begin() + l, a.begin() + r, x);
if (it < a.begin() + l || it >= a.begin() + r)cout << -1 << endl;
else cout << *it << endl;
} else if (t == 2) {
int l, r, x;
cin >> l >> r >> x;
auto it = std::upper_bound(a.begin() + l, a.begin() + r, x);
if (it < a.begin() + l || it >= a.begin() + r)cout << -1 << endl;
else cout << *it << endl;
} else if (t == 3) {
int l, r, x;
cin >> l >> r >> x;
auto it = std::lower_bound(a.begin() + l, a.begin() + r, x);
it--;
if (it < a.begin() + l || it >= a.begin() + r)cout << -1 << endl;
else cout << *it << endl;
} else {
int l, r, x;
cin >> l >> r >> x;
auto it = std::upper_bound(a.begin() + l, a.begin() + r, x);
it--;
if (it < a.begin() + l || it >= a.begin() + r)cout << -1 << endl;
else cout << *it << endl;
}
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
// cin >> T;
T = 1;
while (T--)slu();
}
查看8道真题和解析