tle了一个点求助!
  • 板块P1141 01迷宫
  • 楼主northchen
  • 当前回复3
  • 已保存回复3
  • 发布时间2022/2/13 19:40
  • 上次更新2023/10/28 08:37:56
查看原帖
tle了一个点求助!
642015
northchen楼主2022/2/13 19:40

采用了连通块优化,但还是tle了一个点

#include<iostream>
#include<cstring>
#include<queue>
#include<string>
using namespace std;

typedef pair<int, int> PII;
const int N = 1010, M = 100010;

queue<PII> q1;
char g[N][N];
bool st[N][N];
int cnts[M], tt;
int colour[N][N];
int n, m;

int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

int bfs(int x, int y)
{ 
    if (colour[x][y]) return cnts[colour[x][y]];
    
    memset(st, 0 ,sizeof st);
    int cnt = 1;
    st[x][y] = true;
    q1.push({x, y});
    colour[x][y] = ++tt;
    while (!q1.empty()) {
        PII tmp = q1.front();
        q1.pop();
        for (int i = 0; i < 4; i++) {
            int tx = tmp.first + dx[i], ty = tmp.second + dy[i];
            if (tx < 1 || tx > n || ty < 1 || ty > n ) continue;
            if (!st[tx][ty] && (g[tx][ty] xor g[tmp.first][tmp.second])) {
                q1.push({tx, ty});
                cnt++;
                colour[tx][ty] = colour[x][y];
                st[tx][ty] = true;
            }
        }
    }
    cnts[tt] = cnt;
    return cnt;
}

int main()
{
    char ch;
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++)
            scanf("%1d", &g[i][j]);
    }
    
    while (m--) {
        int x, y;
        scanf("%d%d", &x, &y);
        cout << bfs(x, y) << endl;
    }
    return 0;
}
2022/2/13 19:40
加载中...