UFO
Time limit5sMemory limit256 MB
Simulate K laser shots that each remove the first R cells reaching one layer along a row or column, then find the P by P square with the largest remaining sum.
- Level
Medium7 of 10
- Topics
- Segment tree, Simulation, Prefix sum, Matrix
- Solved
- No attempts yet
Problem
Snakeland's security service damaged a hostile alien ship and forced it to land. The ship is built from unit cubes called compartments. Seen from above it covers a grid of rows and columns, and over the cell in row , column there is a stack of compartments. Layers are numbered from 1 at the ground, so the cell in row , column holds a compartment on layer exactly when .
The compartments are made of a metal that only a laser cuts. Laser devices stand on all four sides of the ship, and each device fires beams perpendicular to its own side. A beam runs horizontally along one row or one column at one fixed layer.
Row 1 is the northmost row and column 1 is the westmost column. A beam fired from the west travels along its row from column 1 towards column , and a beam fired from the east travels from column towards column 1. A beam fired from the north travels along its column from row 1 towards row , and a beam fired from the south travels from row towards row 1.
A beam destroys the first compartments on its path. Looking at one cell at a time in the direction of travel, the beam destroys the compartment on the layer being shot whenever that cell's stack still reaches the layer, and it stops once it has destroyed of them. The compartments above a destroyed one drop by one layer, so destroying a compartment in a cell lowers that cell's stack by 1. When the beam leaves the ship before destroying compartments, it destroys fewer.
After shots the ship is bombed from the air. The bomb covers a grid-aligned square of rows and columns and destroys every compartment left over those cells. Write a program that computes the largest number of compartments one bomb can destroy.
Input
The first line contains five integers , , , , (, , , ).
Each of the next lines contains integers. The -th integer on the -th of these lines is , the number of compartments stacked over the cell in row , column ().
Each of the next lines describes one shot with a letter and two integers. The letter is the side the beam comes from and is one of W, E, S, N. For W and E the first integer is a row number between 1 and ; for N and S it is a column number between 1 and . The second integer is the layer being shot, between 1 and . The shots are processed in the order given.
Output
Print one integer, the largest number of compartments left over any block of cells after all shots.