The Phoenix That Topples the School
Time limit2sMemory limit1024 MB
Given bricks stacked on floors, find the most bricks that can fall after removing one brick, when unsupported bricks collapse floor by floor.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Stack, Tree, Intervals
- Solved
- No attempts yet
Problem
Phoenix was practicing aerobatics in the sky one day when he suddenly decided that the buildings of POSTECH were in the way of his flight. Wanting to fly more freely, he resolved to bring down the school buildings!
The buildings of POSTECH are structured as follows.
- Each building is built by stacking rectangular bricks. All bricks have height , but their widths can differ. Two bricks on the same floor cannot overlap.
- The building has floors in total, each of height . Every floor has at least one brick.
- Every brick in the building is either on floor or directly touches a brick on the floor just below it. Bricks that touch only at a corner do not count as touching. A brick that fails this condition is said to be floating in the air.
In the figure below, building A satisfies all of the conditions above. Building B is not valid because brick 7 is floating in the air.

Building A

Building B
A solidly built building is not easy to topple in an instant. So Phoenix wants to remove exactly brick to bring down as many bricks as possible. The building collapses as follows.
- Phoenix picks and removes one brick on floor .
- Any brick on floor that touched only the removed bricks on floor is now floating. Such bricks are removed immediately, since no floating brick may remain.
- In the same way, the bricks removed in step 2 can leave some bricks on floor floating, and those are removed immediately as well.
- This chain continues one floor at a time until the building collapses. The process ends when no floating brick remains or when the top floor is reached.
Phoenix wants to know in advance how many bricks will fall before he acts. Find the maximum number of bricks that can be brought down on Phoenix's behalf. The brick removed first is also counted among the bricks that fall.
Input
The first line contains the number of bricks and the height of the building , separated by a space. ()
Each of the next lines contains three integers , , and , separated by spaces. This means that brick is on floor , its left end is at x-coordinate on the coordinate plane, and its right end is at x-coordinate . (; )
It is guaranteed that every floor has at least one brick, no two bricks on the same floor overlap, and no brick is floating in the air.
Output
Print the maximum number of bricks that can be brought down by removing exactly one brick.