Codeforces Round #641 (Div. 2) E. Orac and Game of Life

对于某个点,只要它开始变化了,那么之后就一定呈周期性变化,所以我们只需要算出没个位置在第几次迭代开始第一次变化就好了,先把一个连通块元素个数大于2的全部放进去,然后在进行bfs搜出每个位置的dis,表示 到达这里需要最少需要多少次迭代。

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 1e3+10;
#define IOS ios::sync_with_stdio(0)
#define ull unsigned ll
#define uint unsigned
#define pai pair<int,int>
#define pal pair<ll,ll>
#define IT iterator
#define pb push_back
#define fi first
#define se second
#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);i++)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);i--)
#define endl '\n'
#define ll long long
const ll mod = 1e9+7;
int n,m,t;
char str[man][man];
int vis[man][man];
ll dis[man][man];
int to[4][2] = {1,0,-1,0,0,1,0,-1};

struct node{
    int x,y;
    ll dis;
    node(){}
    node(int x,int y,ll dis){
        this->x = x;
        this->y = y;
        this->dis = dis;
    }
};
queue<node>q;


bool check(int x,int y){
    For(i,0,3){
        int to_x = x + to[i][0];
        int to_y = y + to[i][1];
        if(to_x<1||to_x>n||to_y<1||to_y>m||str[x][y]!=str[to_x][to_y])continue;
        return 1; 
    }
    return 0;
}

void bfs(){
    For(i,1,n){
        For(j,1,m){
            dis[i][j] = 2e18;
            if(!vis[i][j]&&check(i,j)){
                vis[i][j] = 1;
                q.push(node(i,j,0));
                dis[i][j] = 0;
            }
        }
    }
    while(!q.empty()){
        node u = q.front();
        q.pop();
        For(i,0,3){
            int to_x = u.x + to[i][0];
            int to_y = u.y + to[i][1];
            if(to_x<1||to_x>n||to_y<1||to_y>m)continue;
            if(u.dis+1<dis[to_x][to_y]){
                dis[to_x][to_y] = u.dis + 1;
                q.push(node(to_x,to_y,u.dis+1));
            }
        }
    }
}

int main() {
    #ifndef ONLINE_JUDGE
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt","w",stdout);
    #endif
    cin >> n >> m >> t;
    For(i,1,n){
        cin >> str[i]+1;
    }
    bfs();
    while(t--){
        int x,y;
        ll p;
        cin >> x >> y >>p;
        char ans;
        //cout << dis[x][y] << endl;
        if(p<=dis[x][y]){
            ans = str[x][y];
        }else{
            ans = ((p-dis[x][y])&1) ? ((str[x][y] - '0')^1 )+'0': str[x][y];
        }
        cout << ans <<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43571920/article/details/106232293