题解:UVA13241 Blade Ranas 2040

· · 题解

题目传送门

题意简述

有一个 R \times C 的网格,每个格子上可能是复制蛙 R、空地 . 或墙壁 #。刀锋蛙可以放在任意一个非墙壁格子上,它能吃掉同行、同列、同对角线上所有视线不被墙壁遮挡的复制蛙。求放在哪个位置能吃掉最多的复制蛙。

思路分析

数据范围很小(R, C \le 100),直接暴力就完了。

直接遍历整个地图,设此时遍历到的坐标为 (i, j),从坐标 (i, j) 出发,向八个方向遍历,在遍历到复制蛙时增加计数,遍历到墙壁之后退出循环。

这个题到这里就结束了。

时间复杂度 O(R \times C \times (R + C))。当 R, C \le 100 时,运算量大约 2 \times 10^{6} 次,轻松通过。

细节优化

如果开了 O2 优化可以忽略这个。

代码实现

直接上代码:

#include <bits/stdc++.h>
using namespace std;

int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int dy[8] = {0, 0, 1, -1, 1, -1, 1, -1};
char grid[105][105];

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    int t;
    cin >> t;

    while (t--) {
        int R, C;
        cin >> R >> C;

        string s;
        for (int i = 1; i <= R; i++) {
            cin >> s;
            for (int j = 1; j <= C; j++) {
                grid[i][j] = s[j - 1];          // 坐标从 (1,1) 开始,方便边界判断
            }
        }

        int ans = -1;
        int acx = 1, acy = 1;

        for (int i = 1; i <= R; i++) {
            for (int j = 1; j <= C; j++) {
                if (grid[i][j] == '#') continue; // 墙壁上不能放
                int cnt = (grid[i][j] == 'R');   // 先算自己这一格

                for (int d = 0; d < 8; d++) {
                    int x = i + dx[d], y = j + dy[d];

                    while (x >= 1 && x <= R
                        && y >= 1 && y <= C
                        && grid[x][y] != '#') {  // 没越界且没被墙挡住
                        cnt += (grid[x][y] == 'R');
                        x += dx[d];
                        y += dy[d];
                    }
                }

                if (cnt > ans) {
                    acx = i;
                    acy = j;
                    ans = cnt;
                }
            }
        }
        cout << acx << " " << acy << endl;
    }
    return 0;
}

觉得有用就点个赞吧!