论卡时的境界(求优化)
  • 板块P1141 01迷宫
  • 楼主jor蛋
  • 当前回复2
  • 已保存回复2
  • 发布时间2021/11/17 11:15
  • 上次更新2023/11/4 00:21:03
查看原帖
论卡时的境界(求优化)
72921
jor蛋楼主2021/11/17 11:15

注意看#2 求优化一下,不用O2也能过

#include<bits/stdc++.h>
using namespace std;
char g[1010][1010];
bool st[1010][1010];
int n,m,deep;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int dist[1010][1010];
int res[505000];
bool check(int x,int y){
    return x>=1&&x<=n&&y>=1&&y<=n;
}
void bfs(int _x,int _y){
    queue<pair<int,int>> q;
    q.push({_x,_y});
    int sum=1;
    deep++;
    memset(st,false,sizeof st);
    st[_x][_y]=true;
    while(q.size()){
        auto t=q.front();
        q.pop();

        for(int i=0;i<4;i++){
            int x=t.first+dx[i],y=t.second+dy[i];
            if(check(x,y)&&!dist[x][y]&&!st[x][y]&&g[x][y]==1-g[t.first][t.second]){
                st[x][y]=true;
                sum++;
                dist[x][y]=deep;
                q.push({x,y});
            }
        }
    }
    res[deep]=sum;
    return ;
}
int main(){
    scanf("%d%d",&n,&m);
    string s;
    for(int i=1;i<=n;i++){
        cin>>s;
        for(int j=1;j<=n;j++)
            g[i][j]=s[j-1]-'0';
    }
    // for(int i=1;i<=n;i++){
    //     for(int j=1;j<=n;j++)
    //         if(!dist[i][j]){
    //             bfs(i,j);
    //             dist[i][j]=deep;
    //         }
    // }
    //res[0]=1;
    while(m--){
        int i,j;
        scanf("%d%d",&i,&j);
        if(!dist[i][j]){
                bfs(i,j);
                dist[i][j]=deep;
            }
        printf("%d\n",res[dist[i][j]]);
    }
}
2021/11/17 11:15
加载中...