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>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define F first
#define S second
#define pb push_back
#define ld long double
#define int ll
#define pll pair <ll,ll>
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define TIME 1.0*clock()/CLOCKS_PER_SEC
using namespace std;
using namespace __gnu_pbds;
mt19937_64 gen(time(0));
int n,q;
vector <int> a;
vector <int> b;
void init() {
cin>>n>>q;
a.resize(n + 2);
b.resize(n + 2);
for (int i = 0;i < n;i++)
cin>>a[i]>>b[i];
}
ll ans = 0;
void output() {
cout<<ans<<'\n';
}
int up[(int)(1e6) ^ 1][(int)(20)];
int sum[(int)(1e6) ^ 1][(int)(20)];
struct sparse_table {
int sp[(int)(1e6) ^ 1][(int)(20)];
inline void build() {
for (int j = 0;j < 20;j++)
{
for (int i = 0;i + (1<<j) <= n;i++)
if (j == 0) sp[i][j] = a[i];
else sp[i][j] = max(sp[i][j - 1],sp[i + (1<<(j - 1))][j - 1]);
}
}
inline int get (int l,int r)
{
int LG = __lg(r - l + 1);
return max(sp[l][LG],sp[r - (1<<LG) + 1][LG]);
}
};
sparse_table ST;
int used[(int)(1e6) ^ 1];
vector <int> gr[(int)(1e6) ^ 1];
inline void dfs (int v,int pr)
{
up[v][0] = pr;
sum[v][0] = b[v];
for (int i = 1;i < 20;i++)
if (up[v][i - 1] != -1) {
up[v][i] = up[up[v][i - 1]][i - 1];
sum[v][i] = sum[up[v][i - 1]][i - 1] + b[v];
}
for (auto to:gr[v])
{
if (to == pr) continue;
dfs(to, v);
}
}
void solve() {
a[n] = 1e18;
b[n] = 0;
++n;
ST.build();
for (int i = 0;i < n;i++)
{
for (int q = 0;q < 20;q++)
up[i][q] = -1;
}
for (int i = 0;i < n;i++)
{
int left = i;
int right = n - 1;
int pos = -1;
while (left <= right) {
int mid = (left + right) >> 1;
if (ST.get(i, mid) != a[i]) {
pos = mid;
right = mid - 1;
}
else left = mid + 1;
}
if (pos != -1) {
gr[pos].pb(i);
gr[i].pb(pos);
}
}
dfs(n - 1,n - 1);
while (q--)
{
int v,k;
cin>>v>>k;
--v;
ans = -1;
int suma = 0;
for (int q = 0;q < 20;q++)
{
//cout<<v<<" "<<sum[v][q]<<" "<<k<<'\n';
if (sum[v][q] >= k) {
if (b[v] >= k) ans = v;
else
ans = up[v][0];
break;
}
else k-=sum[v][q];
v = up[v][q];
suma+=sum[v][q];
}
++ans;
output();
}
}
int32_t main() {
srand(time(0));
//freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
IOS;
int test;
test = 1;
while (test--) {
init();
solve();
}
exit(0);}
/*2 3 3 4*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |