CodeForces - 1350E Orac and Game of Life(bfs)
題目鏈接:點(diǎn)擊查看
題目大意:給出一個 n * m 的 01 矩陣,矩陣每一秒都會迭代,迭代規(guī)則如下:
給出 q 個詢問,每個詢問問格子 ( x , y ) 在第 t 秒迭代后的數(shù)字為多少
題目分析:直接用題解的話來說吧,滿足規(guī)則 1 的點(diǎn)我們稱為 good 點(diǎn),其余的點(diǎn)稱為 bad 點(diǎn),每次迭代,當(dāng)且僅當(dāng)某個點(diǎn)為 good 點(diǎn)時(shí)才發(fā)生迭代,而對于 bad 點(diǎn)而言,如果四周存在至少一個 good 點(diǎn),那么該 bad 點(diǎn)在完成一輪迭代后也會變成 good 點(diǎn),反之不變
換句話說, good 點(diǎn)是會不斷擴(kuò)散的,而 bad 點(diǎn)的數(shù)量相應(yīng)是不增加的,這樣我們就能用 bfs 求出任意一個點(diǎn) ( x , y ) 在整個過程中是否會發(fā)生迭代,在第幾秒時(shí)會發(fā)生迭代,當(dāng)求出這些信息后,就能 O(1) 回答所有詢問了
至于 bfs ,可以視為多源 bfs ,將初始時(shí)為 good 的點(diǎn)全部加入到隊(duì)列中,然后不斷擴(kuò)散就好了,最后判斷的時(shí)候:
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e3+100;const int b[4][2]={0,1,0,-1,1,0,-1,0};int n,m,q;int maze[N][N],f[N][N];bool vis[N][N];bool check(int x,int y) {for(int i=0;i<4;i++){int xx=x+b[i][0];int yy=y+b[i][1];if(xx<=0||yy<=0||xx>n||yy>m)continue;if(maze[x][y]==maze[xx][yy])return true;}return false; }void bfs() {queue<pair<int,int>>q;for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)if(check(i,j)){q.push(make_pair(i,j));vis[i][j]=true;f[i][j]=0;}while(q.size()){int x=q.front().first;int y=q.front().second;q.pop();for(int i=0;i<4;i++){int xx=x+b[i][0];int yy=y+b[i][1];if(xx<=0||yy<=0||xx>n||yy>m)continue;if(vis[xx][yy])continue;f[xx][yy]=f[x][y]+1;vis[xx][yy]=true;q.push(make_pair(xx,yy));}} }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);scanf("%d%d%d",&n,&m,&q);for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%1d",&maze[i][j]);bfs();while(q--){int x,y;LL t;scanf("%d%d%lld",&x,&y,&t);if(vis[x][y])//進(jìn)行過迭代 {if(f[x][y]>t)//沒到迭代時(shí)間 printf("%d\n",maze[x][y]);elseprintf("%d\n",maze[x][y]^((t-f[x][y])&1));}else//沒進(jìn)行過迭代 printf("%d\n",maze[x][y]);}return 0; }?
總結(jié)
以上是生活随笔為你收集整理的CodeForces - 1350E Orac and Game of Life(bfs)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1350B O
- 下一篇: POJ - 1284 Primitive