#include <bits/stdc++.h>
#define dbg(x) cerr << #x << ": " << x << '\n';
#define dbgv(v) cerr << #v << ": "; for(auto &el : v) cerr << el << " "; cerr << '\n';
using namespace std;
using ll = long long;
bool test_cases = 0;
vector<vector<char>> adj;
int calc(int d, int j, vector<int>& s){
    auto l = lower_bound(s.begin(), s.end(), j - d);
    auto r = upper_bound(s.begin(), s.end(), j + d);
    return r - l;
}
void solve(){
    int r, c, d, k;
    cin >> r >> c >> d >> k;
    adj.assign(r, vector<char>(c));
    int m = 0, s = 0;
    vector<pair<int, int>> mpos, spos;
    map<int, map<int, int>> posi;
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            cin >> adj[i][j];
            if(adj[i][j] == 'M'){
                m++;
                mpos.push_back({i, j});
                continue;
            }
            if(adj[i][j] == 'S'){
                s++;
                spos.push_back({i, j});
                posi[i][j] = 1;
            }
        }
    }
    if(r == 1){
        vector<int> s;
        for(auto &[x, y] : spos){
            s.push_back(y);
        }
        int ans = 0;
        for(auto &[x, y] : mpos){
            if(calc(d, y, s) >= k) ans++;
        }
        cout << ans;
        return;
    }
    if(d == max(r, c) and k <= s){
        cout << m;
    } else {
        int ans = 0;
        for(auto &[x, y] : mpos){
            int auxk = 0;
            for(int i = max(x - d, 0); i <= min(r - 1, x + d); i++){
                for(int j = max(y - d, 0); j <= min(c - 1, y + d); j++){
                    if(adj[i][j] == 'S'){
                        auxk++;
                    }
                }
            }
            if(auxk >= k) ans++;
        }
        cout << ans;
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    if(test_cases){
        int t;
        cin >> t;
        for(int i = 0; i < t; i++){
            solve();
        }
        return 0;
    }
    solve();
    return 0;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |