Contest Day 2 - JOI Open Contest
Alice likes a video game named Pinball. The rule of Pinball is as follows.
The board of Pinball is a grid of squares with
A ball appears at one of the squares on the first row of the board, and it falls down vertically towards the bottom of the board. That is to say, if a ball appears in the square
One day, Alice noticed that it is difficult to hit back the ball because a ball can arrive at any squares in the bottom. Alice decided to put some of the following devices on the board appropriately so that there is only one square in the bottom where a ball can possibly arrive.
There are
She needs to pay
Figure: An example of the board of Pinball.
Task
Write a program which, given the size of the board and the information of the devices, calculates the minimum of the total cost needed to put devices on the board so that there is only one square in the bottom where a ball can possibly arrive.
Input Specification
Read the following data from the standard input.
- The first line of input contains two space separated integers
, . This means the board has rows and columns and the number of devices is . - The
line of the following lines contains four space separated integers , , , . This means the device sits in squares from to . The device covers squares in total. The device will transfer a ball arrived at one of these squares to the square . The cost to put the device is yen.
Output Specification
Write one line to the standard output. The output should contain one integer which denotes the minimum of the total cost needed to put devices on the board so that there is only one square in the bottom where a ball can possibly arrive. If it is not possible to put devices satisfying these conditions, write -1
.
Constraints
All input data satisfy the following conditions.
. . . .
Subtasks
Subtask 1 [11 points]
The following conditions are satisfied:
. .
Subtask 2 [18 points]
The following condition is satisfied:
.
Subtask 3 [22 points]
The following condition is satisfied:
.
Subtask 4 [49 points]
No additional constraints.
Sample Input 1
5 6
2 4 3 5
1 2 2 8
3 6 5 2
4 6 4 7
2 4 3 10
Sample Output 1
25
Explanation for Sample 1
The board and the positions of the devices are as in the following figure. The number written above each device denotes the cost needed to put it on the board.
If three devices 2; 4; 5 among five devices are put, the board becomes as in the following figure.
Then, a ball which appears in any square in the first row will arrive at the square
Sample Input 2
3 5
2 4 3 10
1 3 1 20
2 5 4 30
Sample Output 2
-1
Explanation for Sample 2
It is impossible to put devices on the board so that there is only one square in the bottom where a ball can possibly arrive.
Comments