___HatsuneMiku___ @ 2024-07-24 16:43:08
#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;
}
by ___HatsuneMiku___ @ 2024-07-24 17:13:19
我是线性筛,所以马蜂较丑,BFS没学好,希望dalao谅解,orz
by ZYLZPP @ 2024-07-24 17:16:23
@LUO_Never_AC
改成
int BFS(int x, int y)
{
int ans = 1;
queue<Node> q;
q.push({x, y});
vis[x][y] = 1;
vector<Node> pt;
while (!q.empty())
{
Node top = q.front();
pt.push_back(top);
q.pop();
if (mem[top.x][top.y])
{
ans += mem[top.x][top.y];
break;
}
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 (auto &p : pt) mem[p.x][p.y] = ans;
return ans;
}
by ZYLZPP @ 2024-07-24 17:25:55
@LUO_Never_AC
AC了吗?
by ___HatsuneMiku___ @ 2024-07-24 18:28:32
@ZYLZPP AC了,已关