Aarelia Mountains
Time limit2sMemory limit256 MB
Given n region heights and m Earthquake spells with lengths and costs, find the cheapest way to make the heights non-decreasing, or print -1 if it is impossible.
- Level
Hard8 of 10
- Topics
- Graph, Shortest path, Prefix sum
- Solved
- No attempts yet
Problem
You are a powerful wizard travelling across the Aarelia kingdom. Your path lies across a land of steep hills and mountains. The mountain area is a row of regions, and region has elevation .
You have no climbing equipment (and, frankly, no climbing skills), and your Flight spells are used up. You can cross the area only when the elevations form a non-decreasing sequence, that is, for each from 1 to . You travel from right to left, so high falls are no threat.
The only spell that can help is the Earthquake spell. Each Earthquake spell affects several adjacent regions and changes their elevation. You know varieties of the spell. Variety has a range (the number of adjacent regions it affects) and an energy cost , and it either raises or lowers all affected regions by 1. A variety cannot both raise and lower. It can be applied to any range of length that lies completely within the area, and you may cast it an unlimited number of times, paying the energy cost after each cast. Some regions may end up with negative elevation.
Determine whether you can alter the landscape so that you can travel safely, and if so, find the lowest total energy you must spend on casting spells.
Input
The first line contains two integers and ().
The second line contains integers (), the initial elevations of the regions.
The next lines describe the varieties of the Earthquake spell. Line has the form t_i l_i c_i, where t_i is + if the spell raises elevations by 1, or - if it lowers them by 1. Here and .
Output
If travel is possible, print the lowest total energy that must be spent on casting spells. Otherwise, print -1.