https://www.luogu.com.cn/problem/P1141
一开始觉着是个宽搜就兴冲冲地背一了波模板,然后很高兴的TLE三个
所以这题需要优化,不能每个点都跑一边bfs,所以应该将连通块染色,相当于把一条路上的元素都标记成一样的,最后通过一个数组来存每个连通块的长度即可,并查集相同思想
这居然是一道橙题,可能是我太菜了
#include <iostream> #include <algorithm> #include <cstring> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 1010; int g[N][N], idx[N][N], a[1000010]; int n, m; int main() { cin >> n >> m; for(int i = 1; i <= n; i ++ ) for(int j = 1; j <= n; j ++ ) { char c; cin >> c; g[i][j] = c - '0'; } int d = 0; queue<PII> q; for(int i = 1; i <= n; i ++ ) for(int j = 1; j <= n; j ++ ) { if(idx[i][j] == 0) { d ++ ; q.push({i, j}); idx[i][j] = d; int cnt = 1; while(q.size()) { auto t = q.front(); q.pop(); int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; for(int i = 0; i < 4; i ++ ) { int a = t.first + dx[i], b = t.second + dy[i]; if(a >= 1 && a <= n && b >= 1 && b <= n && idx[a][b] == 0) { if(g[t.first][t.second] == 1 && g[a][b] == 0) { cnt ++ ; idx[a][b] = d; q.push({a, b}); } if(g[t.first][t.second] == 0 && g[a][b] == 1) { cnt ++ ; idx[a][b] = d; q.push({a, b}); } } } } a[d] = cnt; } } while(m -- ) { int x, y; cin >> x >> y; cout << a[idx[x][y]] << endl; } return 0; }