Pagini recente » Cod sursa (job #2324737) | Cod sursa (job #2884326) | Cod sursa (job #3142824) | Cod sursa (job #2670201) | Cod sursa (job #3308915)
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <iomanip>
using namespace std;
#define ll long long
struct Node {
int val;
Node* left;
Node* right;
Node(int _val){val = _val; left = nullptr; right = nullptr;}
};
Node* insert(Node* root, int val){
if (root == nullptr) return new Node(val);
if (root->val > val) root->left = insert(root->left, val);
if (root->val < val) root->right = insert(root->right, val);
return root;
}
int minQuery(Node* root, int target) {
int ans = -1; // or some sentinel value if not found
while (root != nullptr) {
if (root->val >= target) {
ans = root->val; // candidate answer
root = root->left; // but maybe there's a smaller one on the left
} else {
root = root->right; // too small, go right
}
}
return ans;
}
int n, m;
Node* root = nullptr;
void ReadData() {
cin >> n >> m;
for (int i = 0; i < n; i++){
int val = 0;
cin >> val;
root = insert(root, val);
}
}
void Solve() {
int x, y;
for(int i = 0; i < m; i++){
Node* fake = root;
cin >> x >> y;
cout << minQuery(fake, x) << " ";
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("rmq.in", "r", stdin);
freopen("rmq.out", "w", stdout);
int t = 1;
// cin >> t; // Uncomment for multiple test cases
while (t--) {
ReadData();
Solve();
}
return 0;
}