Keep it energized
Time limit3sMemory limit256 MB
Buy energy packs at level shops so the stored energy covers each level cost in order for the least total cash.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Segment tree, Prefix sum, Binary search
- Solved
- No attempts yet
Problem
A console maker is building Adventures of Captain Mikado, the game that ships with its new machine. The game has levels numbered through , and level costs exactly units of energy to clear. That is, the player's energy when level starts must be at least , and clearing the level drops the energy by exactly . Winning means clearing every level in increasing order, from level to level , without ever going back to a level that is already cleared.
The player starts with energy . Energy comes from energy packs sold by the shops scattered across the levels. Each shop sells one kind of energy pack, with a strength and a cost . The player can buy an energy pack only from a shop on the level he is currently on, and only before starting that level. Buying a pack of strength sets the energy to at once, whatever it was just before.
Find the smallest amount of in-game cash that clears all levels.
Input
The first line contains the number of levels and the number of shops ().
The second line contains integers , where is the energy needed to clear level ().
Each of the next lines describes one shop with the integers , and . is the level the shop is on, and and are the strength and the cost of the energy pack it sells (, , ).
Output
Print on one line the minimum amount of in-game cash needed to clear all levels. If clearing every level is impossible, print -1.