Tiles on a grid give energy when visited; jump only right or up at cost B, and maximize the energy left on reaching tile N.
Medium7Dynamic programmingGraphSortingNo attempts yetTime limit2sMemory limit512 MBThere are N tiles on a two-dimensional plane. Tile i sits at (xi,yi) and carries one energy bottle that refills your jumping energy by ei.
You jump to the right or up, and nowhere else. A jump from tile (x1,y1) to tile (x2,y2) is allowed when y1=y2 and x1<x2 (to the right), or when x1=x2 and y1<y2 (up). The two tiles do not have to be adjacent. Any tile that lies in that direction on the same row or the same column is a legal landing spot. You cannot jump to a place with no tile.
Every jump costs B energy. You cannot jump while your energy is smaller than B. The moment you land on a new tile you take its energy bottle and your energy grows by ei.
You start on tile 1 with energy e1. Jump from tile 1 to tile N so that the energy left when you arrive at tile N is as large as possible.
Write a program that finds that maximum energy.
The first line contains the number of test cases T. (1≤T≤10)
The first line of each test case contains two integers N and B. (2≤N≤300000, 1≤B≤1000)
The next N lines describe tile 1 through tile N in order. Each line contains three integers xi, yi, ei. (0≤xi,yi≤100000, 0≤ei≤1000)
No two tiles share a coordinate. At least one sequence of jumps from tile 1 to tile N obeys the energy rule.
For each test case, print on one line the maximum energy you can hold when you arrive at tile N.