社区讨论

80分TLE了,加了记忆化搜索(玄关)

P114101迷宫参与者 3已保存回复 13

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
13 条
当前快照
1 份
快照标识符
@lyzlngpw
此快照首次捕获于
2024/07/24 16:45
2 年前
此快照最后确认于
2024/07/24 17:34
2 年前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[1005][1005];
int vis[1005][1005];
int mem[1005][1005];
class Node
{
public:
    int x, y;
};
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int BFS(int x, int y)
{
    int ans = 1;
    queue<Node> q;
    q.push({x, y});
    vis[x][y] = 1;
    while (!q.empty())
    {
        Node top = q.front();
        q.pop();
        // cout << top.x << ' ' << top.y << '\n';
        for (int i = 0; i < 4; i++)
        {
            int tx = top.x + dx[i];
            int ty = top.y + dy[i];
            if (tx >= 1 && tx <= n && ty >= 1 && ty <= n)
                if (a[tx][ty] != a[top.x][top.y] && !vis[tx][ty])
                {
                    q.push({tx, ty});
                    vis[tx][ty] = 1;
                    ans++;
                }
        }
    }
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            if (vis[i][j])
            {
                vis[i][j] = 0;
                mem[i][j] = ans;
            }
    return ans;
}
void solve(void)
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
        {
            char c;
            cin >> c;
            a[i][j] = c - '0';
        }
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        if (!mem[x][y])
        {
            int Ans = BFS(x, y);
            cout << Ans << '\n';
        }
        else
            cout << mem[x][y] << '\n';
    }
    return;
}
int main()
{
    // freopen(".in","r",stdin);
    // freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();

    return 0;
}

回复

13 条回复,欢迎继续交流。

正在加载回复...