Ski Slope

시간 제한2초메모리 제한2048 MB

요약
각 정점 i>1은 p_i로 내려가는 간선을 하나 가지며 난이도 d_i와 즐거움 e_i가 있다. 질의 (s, c)마다 난이도가 s보다 큰 간선을 최대 c개 사용해 정점 1까지 내려갈 때 얻는 최대 즐거움 합을 구한다.
난이도

어려움10점 중 9점

유형
동적 계획법, 그리디, 트리, 이분 탐색
정답자
아직 제출이 없습니다

문제

Bessie is going on a ski trip with her friends. The mountain has NN waypoints (1≤N≤1051\leq N \leq 10^5) labeled 1,2,…,N1, 2, \ldots, N in increasing order of altitude (waypoint 11 is the bottom of the mountain).

For each waypoint i>1i > 1, there is a ski run starting from waypoint ii and ending at waypoint p_ip\_i (1≤p_i\<i1\le p\_i\<i). This run has difficulty d_id\_i (0≤d_i≤1090 \leq d\_i \leq 10^9) and enjoyment e_ie\_i (0≤e_i≤1090 \leq e\_i \leq 10^9).

Each of Bessie's MM friends (1≤M≤1051\leq M \leq 10^5) will do the following: They will pick some initial waypoint ii to start at, and then follow the runs downward (to p_ip\_i, then to p_p_ip\_{p\_i}, and so forth) until they get to waypoint 11.

The enjoyment each friend gets is equal to the sum of the enjoyments of the runs they follow. Each friend also has a different skill level s_js\_j (0≤s_j≤1090 \leq s\_j \leq 10^9) and courage level c_jc\_j (0≤c_j≤100 \leq c\_j \leq 10), which limits them to selecting an initial waypoint that results in them taking at most c_jc\_j runs with difficulty greater than s_js\_j.

For each friend, compute the maximum enjoyment they can get.

입력

The first line contains NN.

Then for each ii from 22 to NN, a line follows containing three space-separated integers p_ip\_i, d_id\_i, and e_ie\_i.

The next line contains MM.

The next MM lines each contain two space-separated integers s_js\_j and c_jc\_j.

출력

Output MM lines, with the answer for each friend on a separate line.

Note that the large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a "long long" in C/C++).

예제1

  1. 예제 1

    입력
    4
    1 20 200
    2 30 300
    2 10 100
    8
    19 0
    19 1
    19 2
    20 0
    20 1
    20 2
    29 0
    30 0
    
    예상 출력
    0
    300
    500
    300
    500
    500
    300
    500