<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

463. Walking around Berhattan
Time limit per test: 0.25 second(s)
Memory limit: 65536 kilobytes
input: standard
output: standard

As you probably know, Berhattan is a district of Berland's largest city and it consists of equal square blocks. There are n block lines in the east-west direction and m block lines in the south-north direction. The map shows Berhattan as a rectangle with n rows and m columns, so there are nx m blocks in total.

There are n+1 streets running parallel in the east-west direction (horizontally), and there are m+1 avenues running parallel in the south-north direction (vertically). Streets and avenues split the district into blocks and separate Berhattan from other districts of Berland. Each block in Berhattan is characterized by its beauty bij.

A pedestrian can walk only along streets and avenues. When the pedestrian walks along any of four sides of a block, we say he passes the block. Every time the pedestrian passes a block his satisfaction is increased by bij. If the pedestrian has already passed the block one or more times his satisfaction is increased only by bij/2 rounded down when he passes the block again.

You are given the map of Berhattan with the information about the blocks' beauty and the pedestrian's path along the streets and avenues. The path is given as a string containing letters 'L', 'R' and 'M', where 'L' means a 90 degree left turn, 'R' means a 90 degree right turn, and 'M' means walking one block forward by a street or avenue. Facing the east, the pedestrian starts his path in the north-west corner of Berhattan having zero satisfaction level. His path can cross itself and go along the same streets or avenues several times. Pedestrian's satisfaction is increased every time he moves according to the rules described above.

Your task is to calculate the total satisfaction the pedestrian will get after finishing his route.


Picture of the sample test


Input
The first line of input contains two integers n and m (1 ≤ n,m ≤ 100), where n is a number of block lines in Berhattan running in the east-west direction, and m is a number of block lines in Berhattan running in the south-north direction. The following n lines contain m digits each. The j-th digit of the i-th line represents bij (0 ≤ bij ≤ 9) — the beauty of the corresponding block. The last line of input contains a path in the format specified above. The path consists of 1 up to 500 characters, inclusively. It is guaranteed that the given path doesn't go outside Berhattan.

Output
Print a single integer to the output — the total pedestrian's satisfaction.

Example(s)
sample input
sample output
3 3
123
456
789
MRMMLM
22

<|response|>
1) Abridged problem statement
- You have an n×m grid of square blocks (beauty values 0–9). Streets/avenues form the grid lines, so intersections are at (m+1)×(n+1) points.
- A pedestrian starts at the north-west corner intersection, facing east. A path string uses:
  - L: turn left 90°
  - R: turn right 90°
  - M: move forward by one block (one street segment)
- When moving one segment, the pedestrian “passes” the adjacent block(s) of that segment:
  - 2 blocks if the segment is internal; 1 block if it lies on the border.
- Scoring:
  - First time a block is passed: +bij
  - Each subsequent time: +floor(bij/2)
- The path never leaves the map. Compute the final satisfaction.

2) Key observations
- Intersections form a grid with coordinates:
  - x in [0, m] (west→east), y in [0, n] (north→south); start at (0, 0), facing east.
- Directions can be encoded cyclically:
  - 0: east, 1: south, 2: west, 3: north
  - L: dir = (dir + 3) % 4; R: dir = (dir + 1) % 4
- On each move M from (x, y) to (nx, ny), identify adjacent blocks by direction:
  - East: above (y-1, x) if y>0; below (y, x) if y<n
  - South: left (y, x-1) if x>0; right (y, x) if x<m
  - West: above (y-1, x-1) if y>0 and x>0; below (y, x-1) if x>0
  - North: left (y-1, x-1) if y>0 and x>0; right (y-1, x) if y>0 and x<m
- We only need to know whether a block has been passed before (boolean), not the exact count, because scoring is “first time vs later times”.
- Complexity is O(|path|), with |path| ≤ 500, easily within limits.

3) Full solution approach
- Read n, m, the grid of digits (beauties), and the path.
- Maintain:
  - Current intersection (x, y) and direction dir (start at 0:east).
  - A visited[n][m] boolean grid, initially false.
  - A running total satisfaction.
- For each character in path:
  - If L or R, update dir accordingly.
  - If M:
    - Compute the next intersection (nx, ny) = (x + dx[dir], y + dy[dir]).
    - Based on dir, identify 1 or 2 adjacent blocks (check boundaries).
    - For each adjacent block (r, c):
      - beauty = grid[r][c]
      - If visited[r][c] is false: add beauty; set visited[r][c] = true
      - Else: add beauty // 2
    - Update (x, y) = (nx, ny).
- Output the final satisfaction.

4) C++ implementation with detailed comments
```cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    if (!(cin >> n >> m)) return 0;

    vector<string> rows(n);
    for (int i = 0; i < n; ++i) cin >> rows[i];

    string path;
    cin >> path;

    // Convert grid of digits to integer beauties
    vector<vector<int>> beauty(n, vector<int>(m));
    for (int r = 0; r < n; ++r)
        for (int c = 0; c < m; ++c)
            beauty[r][c] = rows[r][c] - '0';

    // visited[r][c] = has block (r,c) been passed before?
    vector<vector<bool>> visited(n, vector<bool>(m, false));

    // Intersections: x in [0..m], y in [0..n]
    int x = 0, y = 0;    // start at north-west corner
    int dir = 0;         // 0:east, 1:south, 2:west, 3:north
    const int dx[4] = {1, 0, -1, 0};
    const int dy[4] = {0, 1, 0, -1};

    long long total = 0;

    auto pass_block = [&](int r, int c) {
        int b = beauty[r][c];
        if (!visited[r][c]) {
            total += b;
            visited[r][c] = true;
        } else {
            total += b / 2;
        }
    };

    for (char ch : path) {
        if (ch == 'L') {
            dir = (dir + 3) % 4;
        } else if (ch == 'R') {
            dir = (dir + 1) % 4;
        } else {
            int nx = x + dx[dir];
            int ny = y + dy[dir];

            // Add contributions from blocks adjacent to the traversed segment
            if (dir == 0) { // east: segment from (x,y) to (x+1,y)
                if (y > 0 && x < m) pass_block(y - 1, x); // above
                if (y < n && x < m) pass_block(y, x);     // below
            } else if (dir == 1) { // south: segment from (x,y) to (x,y+1)
                if (y < n && x > 0) pass_block(y, x - 1); // left
                if (y < n && x < m) pass_block(y, x);     // right
            } else if (dir == 2) { // west: segment from (x,y) to (x-1,y)
                if (y > 0 && x > 0) pass_block(y - 1, x - 1); // above
                if (y < n && x > 0) pass_block(y, x - 1);     // below
            } else { // dir == 3, north: segment from (x,y) to (x,y-1)
                if (y > 0 && x > 0) pass_block(y - 1, x - 1); // left
                if (y > 0 && x < m) pass_block(y - 1, x);     // right
            }

            x = nx;
            y = ny;
        }
    }

    cout << total << '\n';
    return 0;
}
```

5) Python implementation with detailed comments
```python
import sys

def main():
    data = sys.stdin.read().strip().splitlines()
    it = iter(data)
    n, m = map(int, next(it).split())

    # Read grid rows as strings; convert to int beauties
    rows = [next(it).strip() for _ in range(n)]
    beauty = [[ord(ch) - ord('0') for ch in row] for row in rows]

    path = next(it).strip()

    # visited[r][c] = has block (r,c) been passed before?
    visited = [[False] * m for _ in range(n)]

    # Intersections: x in [0..m], y in [0..n]
    x, y = 0, 0              # start at north-west corner
    dir = 0                  # 0:east, 1:south, 2:west, 3:north
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    total = 0

    def pass_block(r, c):
        nonlocal total
        b = beauty[r][c]
        if not visited[r][c]:
            total += b
            visited[r][c] = True
        else:
            total += b // 2

    for ch in path:
        if ch == 'L':
            dir = (dir + 3) % 4
        elif ch == 'R':
            dir = (dir + 1) % 4
        else:  # 'M'
            nx = x + dx[dir]
            ny = y + dy[dir]

            if dir == 0:  # east
                if y > 0 and x < m:
                    pass_block(y - 1, x)   # above
                if y < n and x < m:
                    pass_block(y, x)       # below
            elif dir == 1:  # south
                if y < n and x > 0:
                    pass_block(y, x - 1)   # left
                if y < n and x < m:
                    pass_block(y, x)       # right
            elif dir == 2:  # west
                if y > 0 and x > 0:
                    pass_block(y - 1, x - 1)  # above
                if y < n and x > 0:
                    pass_block(y, x - 1)      # below
            else:  # dir == 3, north
                if y > 0 and x > 0:
                    pass_block(y - 1, x - 1)  # left
                if y > 0 and x < m:
                    pass_block(y - 1, x)      # right

            x, y = nx, ny

    print(total)

if __name__ == "__main__":
    main()
```