#include <bits/stdc++.h>
#define GOOD_LUCK ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long
#define itn int
#define endl "\n"
#define ff first
#define ss second
#define pb push_back
#define ppb pop_back
#define ins insert
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define count1 __builtin_popcount
#define all(v) v.begin(), v.end()
using namespace std;
struct point{
};
int ctoi(char x) {
return (int)x - '0';
}
int sumab(int a, int b) {
return (a + b) * (b - a + 1) / 2;
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a%b);
}
int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
void print(vector <int> &v) {
for (const int &i : v) cout << i << ' ';
}
constexpr int MAX = 1e+5 + 3, INF = 2e+9, MOD = 16714589, K = 18;
int temp, temp1, temp2, temp3;
vector <int> g;
pair<int, int> up[K+3][MAX];
void _() {
int n, q;
cin >> n >> q;
vector <int> v(n+1), dia(n+1);
for (int i=1; i <= n; i++) {
cin >> dia[i] >> v[i];
}
v[0] = dia[0] = INF;
g.assign(n+1, 0);
// build tree
// O(n * log(n))
multiset <pair<int, int>> ms;
ms.ins({dia[1], 1});
for (int i=2; i <= n; i++) {
while (!ms.empty()) {
auto b = *ms.begin();
if (b.ff < dia[i]) {
g[b.ss] = i;
ms.erase(ms.find(b));
}
else break;
}
ms.ins({dia[i], i});
}
while (!ms.empty()) {
auto b = *ms.begin();
if (b.ff < dia[0]) {
g[b.ss] = 0;
ms.erase(ms.find(b));
}
else break;
}
// correct
// build up
// O(n + n * log(n))
for (int i=1; i <= n; i++) {
up[0][i] = {g[i], v[i]};
}
for (int i=1; i <= K; i++) {
for (int j=1; j <= n; j++) {
up[i][j].ss = up[i-1][j].ss + up[i-1][up[i-1][j].ff].ss;
up[i][j].ff = up[i-1][up[i-1][j].ff].ff;
if (up[i][j].ff == 0) {
for (int z=i+1; z <= K; z++) {
up[z][j].ss = INF;
}
break;
}
}
}
// correct
// queries
// O(q * log(n))
while (q--) {
int x, y;
cin >> x >> y;
for (int i=K; i >= 0; i--) {
if (up[i][x].ss == y) {
for (int j=i-1; j >= 0; j--) {
x = up[i][x].ff;
}
y = 0;
// cout << "<" << i << ">";
break;
}
else if (up[i][x].ss < y && up[i][x].ss != 0) {
y -= up[i][x].ss;
x = up[i][x].ff;
// cout << "Minus: " << i << ' ' << up[i][x].ss << endl;
}
// cout << x << endl;
}
cout << x << endl;
}
}
signed main() {
GOOD_LUCK
int tests=1;
// cin >> tests;
while (tests--) {
_();
// cout << endl;
}
return 0;
}
// Problem X
// by Ekber_Ekber
/*
8 6
3 5
4 3
2 2
1 3
3 8
5 10
4 5
7 30
4 10
1 3
7 35
6 38
5 8
2 50
8 1
3 5
4 3
2 2
1 3
3 8
5 10
4 5
7 30
7 35
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |