This page is still under construction.

Parts of this page are still being built. What you see may change.

Apples and Bananas

Interview

Time limit1sMemory limit256 MB

Summary
Pick a path from the top left to the bottom right using right, down, and diagonal steps to maximize apples left below plus bananas left above.
Level

Medium6 of 10

Topics
Dynamic programming, Prefix sum
Solved
No attempts yet

Problem

Two neighbouring villages, A and B, cannot settle a land dispute. The disputed area is a rectangle of R×CR \times C cells, and every cell holds either some apple trees or some banana trees.

An outside advisor was asked to mediate. He decided to send one bulldozer across the area and cut down every tree in the cells it passes. The bulldozer starts at the top left cell and always moves in one of three directions: right, down, or diagonally down and to the right. It stops when it reaches the bottom right cell.

Village A takes the land below the track and village B takes the land above it. In each row, the cells to the left of the cells the bulldozer passed are below the track, and the cells to the right of them are above the track. A village can end up with no cell at all.

The people of village A like apples and the people of village B like bananas. The advisor therefore picks the track that maximizes the number of apple trees left below it plus the number of banana trees left above it. Write a program that computes this maximum total.

Input

The first line contains two integers RR and CC (2≤R,C≤15002 \le R, C \le 1500), the size of the area.

Each of the next RR lines contains the descriptions of CC cells, separated by spaces. A description is the letter A (apples) or B (bananas) followed by the number of trees in that cell. Every cell holds between 11 and 9999 trees.

Output

Print the maximum total described above.

Note

In the first example the bulldozer moves diagonally down and to the right, again diagonally down and to the right, then down. That leaves 3+2+4=93 + 2 + 4 = 9 apple trees below the track and 3+5=83 + 5 = 8 banana trees above it.

Examples6

  1. Example 1

    Input
    4 3
    B2 B3 B5
    A3 B1 A1
    A2 A4 B1
    B1 B3 A3
    
    Expected output
    17
    
  2. Example 2

    Input
    3 5
    A5 A2 B3 A6 B2
    A1 B20 A5 B3 B6
    A3 A5 B3 B8 A3
    
    Expected output
    37
    
  3. Example 3

    Input
    2 2
    A9 A9
    B9 B9
    
    Expected output
    0
    
  4. Example 4

    Input
    2 2
    B1 B99
    A99 A1
    
    Expected output
    198
    
  5. Example 5

    Input
    2 8
    B7 A4 B9 A1 B3 B8 A2 B6
    A5 A9 B2 A7 A1 B4 A8 A3
    
    Expected output
    40
    
  6. Example 6

    Input
    8 2
    A6 B1
    B4 A9
    A2 A5
    B8 B3
    A7 A1
    B2 B9
    A4 A6
    B5 A2
    
    Expected output
    17