This page is still under construction.

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

Collecting Mushrooms

Time limit1sMemory limit512 MB

Summary
Given a grid with mushrooms and sprinklers, count mushrooms covered by at least K sprinklers within Chebyshev distance D.
Level

Medium6 of 10

Topics
Prefix sum, Matrix, Implementation, Brute force
Solved
No attempts yet

Problem

Lim Li the Crab runs a mushroom plantation in her backyard. Her mushroom plantation can be modelled as a grid of R rows and C columns, and each cell can either be empty, contain a mushroom, or contain a sprinkler. For example, her plantation could look like this:

Figure 1: A mushroom farm with R = 5 and C = 5.

The distance between a sprinkler and a mushroom is the larger of their separations along the two axes. In other words, if the mushroom is at row Xm and column Ym and the sprinkler is at row Xs and column Ys, their distance is max(|Xs − Xm|, |Ys − Ym|). A sprinkler has a limited range, so it can water a mushroom only if the distance between them is at most D. For example, if D = 1, the areas the two sprinklers reach are:

Figure 2: The range of the sprinklers.

A mushroom can grow and be harvested only when enough sprinklers water it. Specifically, a mushroom is harvestable if at least K sprinklers water it. Count the number of harvestable mushrooms Lim Li can collect in her plantation.

Input

The first line of input contains four integers: R, the number of rows, C, the number of columns, D, the maximum distance between a sprinkler and a mushroom it waters, and K, the minimum number of sprinklers needed for a mushroom to be harvestable.

The next R lines of input contain C characters each, forming a grid that represents the mushroom plantation. Each character represents the contents of one cell:

  • '.' is an empty cell,
  • 'M' is a cell containing a mushroom,
  • 'S' is a cell containing a sprinkler.

Output

Print one line with one integer, the maximum number of mushrooms Lim Li can harvest.

Constraints

  • 2 ≤ RC ≤ 500000,
  • 1 ≤ D ≤ max(R, C),
  • 1 ≤ K ≤ RC,
  • there is at least one mushroom,
  • there is at least one sprinkler.

Examples4

  1. Example 1

    Input
    5 5 1 1
    ....M
    .M...
    ..S..
    .S...
    ...M.
    
    Expected output
    1
    
  2. Example 2

    Input
    4 4 4 1
    ....
    .M..
    ..MM
    ...S
    
    Expected output
    3
    
  3. Example 3

    Input
    1 8 5 2
    SM..MM.S
    
    Expected output
    2
    
  4. Example 4

    Input
    5 5 2 2
    ....M
    .M...
    ..S..
    .S...
    ...M.
    
    Expected output
    2