Cod sursa(job #3308915)

Utilizator alesiodemiriAlesio Demiri alesiodemiri Data 29 august 2025 23:20:38
Problema Range minimum query Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#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;
}