Under construction

Still being built. Things may change

Dungeons Game

Time limit4sMemory limit2048 MB

Summary
Given n dungeons with opponents of strength s[i] and q starting states (dungeon x, strength z), find the hero's final strength when the hero reaches dungeon n.
Level

Hard9 of 10

Topics
Dynamic programming, Tree, Divide and conquer
Solved
No attempts yet

Problem

Robert is designing a new computer game. The game has one hero, nn opponents, and n+1n + 1 dungeons. The opponents are numbered from 00 to n−1n - 1, and the dungeons are numbered from 00 to nn. Opponent ii (0≤i≤n−10 \le i \le n - 1) is in dungeon ii and has strength s[i]s[i]. Dungeon nn has no opponent.

The hero starts by entering dungeon xx with strength zz. Each time the hero enters dungeon ii (0≤i≤n−10 \le i \le n - 1), the hero fights opponent ii, and one of the following happens:

  • If the hero's strength is at least s[i]s[i], the hero wins. The hero's strength increases by s[i]s[i] (s[i]≥1s[i] \ge 1). The hero then enters dungeon w[i]w[i] next (w[i]>iw[i] > i).
  • Otherwise, the hero loses. The hero's strength increases by p[i]p[i] (p[i]≥1p[i] \ge 1). The hero then enters dungeon l[i]l[i] next.

p[i]p[i] may be less than, equal to, or greater than s[i]s[i]. l[i]l[i] may also be less than, equal to, or greater than ii. The opponent stays in dungeon ii with strength s[i]s[i] regardless of the result.

The game ends when the hero enters dungeon nn. The game ends after a finite number of fights no matter which dungeon and strength the hero starts with.

Robert wants to test the game with qq simulations. Each simulation gives a starting dungeon xx and a starting strength zz. For each simulation, find the hero's strength when the game ends.

Constraints

  • 1≤n≤400 0001 \le n \le 400\,000
  • 1≤q≤50 0001 \le q \le 50\,000
  • 1≤s[i],p[i]≤1071 \le s[i], p[i] \le 10^7 (for all 0≤i≤n−10 \le i \le n - 1)
  • 0≤l[i],w[i]≤n0 \le l[i], w[i] \le n (for all 0≤i≤n−10 \le i \le n - 1)
  • w[i]>iw[i] > i (for all 0≤i≤n−10 \le i \le n - 1)
  • 0≤x≤n−10 \le x \le n - 1
  • 1≤z≤1071 \le z \le 10^7

Examples1

  1. Example 1

    Input
    1 1
    1
    1
    1
    0
    0 1
    
    Expected output
    2