Stop, Yesterday Please No More

Stop, Yesterday Please No More

网格图,二维差分

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
// U D L R
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
map<char, int> mp = {{'U', 0}, {'D', 1}, {'L', 2}, {'R', 3}};

void solve() {
    int n, m, k; cin >> n >> m >> k;
    string s; cin >> s;
    set<pair<int, int>> all;
    set<int> px, py;
    int len = s.size();
    int tx = 0, ty = 0; all.insert({0, 0});
    for(int i = 0; i < len; i ++) {
        int id = mp[s[i]];
        tx += dx[id], ty += dy[id];
        // 如果存在超出距离,直接输出
        if(tx <= -n || tx >= n || ty <= -m || ty >= m) {
            if(k != 0) cout << "0\n";
            else cout << n * m << "\n";
            return;
        }
        all.insert({tx, ty});
        px.insert(tx), py.insert(ty);
    }

    int mx = 0, nx = 1e7, my = 0, ny = 1e7; //方块的边界
    for(int i = 1; i <= n; i ++) for(int j = 1; j <= m; j ++) {
        int up = i, down = n - i + 1, left = j, right = m - j + 1;
        if(px.count(up) || px.count(down)) continue;
        if(py.count(left) || py.count(right)) continue;
        mx = max(i, mx), my = max(j, my);
        nx = min(i, nx), ny = min(j, ny);
    }

    int res = (mx - nx + 1) * (my - ny + 1);
    int need = res - k;
    vector<vector<int>> dif(n + 2, vector<int>(m + 2, 0));
    for(auto [x, y] : all) {
        dif[x + nx][y + ny] ++;
        dif[x + nx + 1][y + ny] --;
        dif[x + nx][y + ny + 1] --;
        dif[x + nx + 1][y + ny + 1] ++;
    }

    int ans = 0;
    for(int i = 1; i <= n; i ++) for(int j = 1; j <= m; j ++) {
        dif[i][j] = dif[i][j - 1] + dif[i - 1][j] - dif[i - 1][j - 1];
        if(dif[i][j] == need) ans ++;
    }
    cout << ans << "\n";
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int _ = 1; cin >> _;
    while(_--) solve();
    return 0;
}
posted @ 2026-11-03 22:04  thenrify  阅读(2)  评论(0)    收藏  举报