Find the largest axis-aligned square that fits on the grid so the total cost of removing the obstacles it overlaps stays within budget.
Medium7Binary searchSegment treeGeometryNo attempts yetTime limit5sMemory limit128 MBYou need the largest pyramid site your budget allows. A land survey divides the site into an M×N grid of square cells. The base of the pyramid must be a square with sides parallel to the grid.
The survey found P obstacles. Each obstacle is a rectangle with sides parallel to the grid, and obstacles may overlap. To build the pyramid, every cell covered by its base must be cleared of obstacles. Removing obstacle i costs Ci. An obstacle can only be removed whole, never in part. Removing one obstacle leaves any obstacle that overlaps it untouched.
Given the dimensions M and N, the position and removal cost of each of the P obstacles, and the budget B, write a program that finds the largest possible side length of the base such that the total removal cost does not exceed B.
The first line contains M and N, separated by one space. (1≤M,N≤106)
The second line contains the budget B. (0<B≤2×109)
The third line contains P, the number of obstacles. (1≤P≤30000)
Each of the next P lines describes one obstacle. The ith of these lines describes obstacle i and contains five integers Xi1, Yi1, Xi2, Yi2, Ci, separated by single spaces. The first two are the coordinates of the bottommost leftmost cell of the obstacle, the next two are the coordinates of the topmost rightmost cell, and the last is the cost of removing that obstacle. The bottommost leftmost cell of the grid has coordinates (1,1) and the topmost rightmost cell has coordinates (M,N). (1≤Xi1≤Xi2≤M, 1≤Yi1≤Yi2≤N, 1≤Ci≤7000)
Print one integer, the largest side length of the base that can be prepared. If no pyramid can be built at all, print 0.

The figure shows two placements of a base with side length 4.