Find the side length of the largest axis-aligned square on a grid that avoids all given rectangular obstacles.
Hard8Binary searchGeometrySegment treeSortingNo attempts yetTime limit5sMemory limit128 MBYou are looking for the largest site where the base of a new pyramid can stand. A survey has divided the available land into a grid of M columns and N rows of square cells. The base of the pyramid is a square, and its sides must be parallel to the sides of the grid.
The survey found P obstacles, which may overlap each other. Every obstacle is a rectangle whose sides are parallel to the sides of the grid. To build the pyramid, no obstacle may remain on any cell that the base covers. Removing obstacle i costs Ci, and an obstacle is always removed as a whole. You cannot remove only part of an obstacle. Removing one obstacle leaves every obstacle that overlaps it in place.
You are given the grid size M and N, the position and the removal cost of each of the P obstacles, and the budget B. Write a program that finds the largest side length of a base you can prepare while the total removal cost stays within B.
The first line contains M and N, separated by a single space. (1≤M,N≤1000000)
The second line contains the budget B. In this problem B is always 0.
The third line contains P, the number of obstacles. (1≤P≤400000)
Each of the next P lines describes one obstacle. The ith of those lines contains five integers Xi1, Yi1, Xi2, Yi2, Ci, separated by single spaces. The first four are the coordinates of the bottommost leftmost cell and of the topmost rightmost cell of obstacle i, and Ci 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)
On the first line, print the largest side length of a pyramid base you can prepare. If no pyramid can be built at all, print 0.

The figure shows the layout of the example. The square drawn there is the only place where a base of side length 3 fits.