CF198B 题解
Federico2903 · · 题解
题意
这是一道练习 BFS 的好题。
设忍者的位置为
最初忍者在左墙的最下方,当忍者到达了一个高度大于
但峡谷被水淹没了,每秒水位会上升一米。我们设忍者已经爬了
如果忍者曾经到达过一个区域,我们就不必再前往那个区域,否则会出现重复的情况。
我们用一个二维数组来表示两堵墙,
如果一个地方是危险的,我们亦可将其看作是曾经走过(都属于不可取的情况),所以当
然后用 BFS 广搜,从左下角开始,每次扩展三个节点(上,下,异侧跳)。
更多细节见代码注释。
AC 代码
#include<bits/stdc++.h>
using namespace std;
int n,k;
int wall[100005][2];//标记数组
string leftw,rightw;
struct pos{//用来表示忍者的位置
int h,t;//h为忍者的高度,t为忍者用了的时间
int way;//忍者在哪堵墙 0为左 1为右
pos(){}
pos(int h,int t,int way){//构造函数
this->h=h;
this->t=t;
this->way=way;
}
};
queue<pos> q;
void bfs(pos start){
q.push(start);
wall[1][0]=1;//标记左下角走过了
while(!q.empty()){
pos t=q.front();
q.pop();
if(t.h-1>0&&!wall[t.h-1][t.way]&&t.h-1>t.t+1){//向下走
wall[t.h-1][t.way]=1;//打标记
q.push(pos(t.h-1,t.t+1,t.way));//扩展
}
if(t.h+1>n){//向上走可以直接走出
cout << "YES";
return;//离开了峡谷
}
if(!wall[t.h+1][t.way]&&t.h+1>t.t+1){//向上走无法直接走出
wall[t.h+1][t.way]=1;
q.push(pos(t.h+1,t.t+1,t.way));//扩展
}
if(t.h+k>n){//向另一边跳直接离开峡谷
cout << "YES";//离开了峡谷
return;
}
if(!wall[t.h+k][!t.way]&&t.h+k>t.t+1){//扩展异侧跳
wall[t.h+k][!t.way]=1;
q.push(pos(t.h+k,t.t+1,!t.way));
}
}
cout<<"NO";//所有可能性都无法逃出峡谷,输出NO
return;
}
int main(){
cin >> n >> k;
cin >> leftw >> rightw;
for(int i=1;i<=n;i++){
if(leftw[i-1]=='X'){
wall[i][0]=1;
}
if(rightw[i-1]=='X'){
wall[i][1]=1;
}//处理字符串
}
bfs(pos(1,0,0));//从左下角开始搜索
return 0;
}