This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std ;
#define ff first
#define ss second
#define ll long long
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define ones(x) __builtin_popcount(x)
#define remove(v)  v.erase(unique(all(v)), v.end())
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define per(i, a, b) for(int i = a; i >= b; i--)
#ifdef local
#include "C:\debug.h"
#else
#define dbg(x...) 42
#endif
#define int ll
const int N = 1e5 + 2 ;
vector<vector<int>> dp(N, vector<int>(20 , 0)) ;
int n , q , d[N] , c[N] , up[N][20] , used[N] ;
vector<int> g[N] ;
void dfs(int v , int p) {
    used[v] = 1 ;
    up[v][0] = p ;
    rep(i , 1 , 17) {
        up[v][i] = up[up[v][i - 1]][i - 1] ;
    }
    for(auto& to : g[v]) {
        if(to != p) {
            dfs(to , v) ;
        }
    }
}
void solve(){
    cin >> n >> q ;
    rep(i , 1 , n) {
        cin >> d[i] >> c[i] ;
    }
    stack<pair<int,int>> s ;
    per(i , n , 1){
        while(sz(s) && s.top().first <= d[i]) s.pop() ;
        if(sz(s)) g[s.top().second].pb(i) ;
        s.push({d[i] , i}) ;
    }
    per(i , n , 1) {
        if(!used[i]) {
            int pr = i ;    
            dfs(i , pr) ;
        }
    }
    per(i , n , 1) {
        dp[i][0] = c[i] ;
        int j = 0 ;
        // cout << dp[i][j] << ' ' ;
        rep(k , 0 , 17) {
            j++ ;
            if(k > 0 && up[i][k] == up[i][k - 1]) {
                dp[i][j] = dp[i][j - 1] ;
            }else
                dp[i][j] = dp[i][j - 1] + c[up[i][k]] ;
            // cout << dp[i][j] << ' ' ;
        }
        // cout << "\n" ;
    }
    rep(i , 1 , q) {
        int ind , k ; cin >> ind >> k ;
        while(k > 0) {
            auto it = upper_bound(all(dp[ind]) , k) ;
            if(it == dp[ind].begin()) {
                ind = up[ind][0] ;
                break ;
            }
            it-- ;
            k -= *it ;
            int pos = it - dp[ind].begin() ;
            if(pos > 0) ind = up[ind][pos - 1] ;
            else{
                it++ ;
            }
        }
        cout << ind << "\n" ;
    }
}
signed main () {
	ios::sync_with_stdio(false) ;
	cin.tie(0) ;
	int test = 1 ;
	// cin >> test ; 
	for(int i = 1 ; i <= test ; i++) {
		solve() ;
	}
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |