Apple Market

Time limit2sMemory limit512 MB

Summary
Given a grid of apple inventories and rectangle requests with budgets, sell apples to maximize total money where each apple costs 1.
Level

Medium7 of 10

Topics
Greedy, Sorting, Prefix sum
Solved
No attempts yet

Problem

You manage a market made up of several stores. The stores are arranged in an n×mn \times m grid, and every store sells apples. At every store, one apple costs exactly 1 Malaysian Ringgit.

Several customers walk through this market. Each customer visits only the stores inside one subrectangle of the market and has a fixed amount of money to spend. Each store has a limited inventory of apples, which differs from store to store and is not replenished between customers. If you can decide how many apples each store sells to each customer, what is the most money you can make?

Input

The input consists of a single test case. Your program may be run several times on different inputs. The first line contains three space-separated integers nn, mm, and kk: the market has nn rows and mm columns (1≤n,m≤501 \le n, m \le 50), and there are kk customers (1≤k≤1051 \le k \le 10^5).

Each of the next nn lines contains mm integers aa (0≤a≤1090 \le a \le 10^9). This matrix, in row-major order, gives the number of apples in the inventory of each store. a[r,c]a[r, c] is the number of apples in the store in row rr, column cc. Rows are numbered 11 to nn and columns 11 to mm. The top left corner is a[1,1]a[1, 1] and the bottom right corner is a[n,m]a[n, m].

Each of the next kk lines describes one customer with five integers tt, bb (1≤t≤b≤n1 \le t \le b \le n), ll, rr (1≤l≤r≤m1 \le l \le r \le m), and xx (0≤x≤1090 \le x \le 10^9). The customer shops only in the subrectangle from (t,l)(t, l) to (b,r)(b, r) inclusive (tt is top, bb is bottom, ll is left, rr is right). The customer has exactly xx Malaysian Ringgits to spend.

Output

Print a single integer: the maximum amount of money you can make by deciding how many apples each store sells to each customer.

Examples1

  1. Example 1

    Input
    2 3 2
    1 2 3
    4 5 6
    1 2 2 3 20
    2 2 1 3 15
    
    Expected output
    20