广搜提高③
_yang_yi_bo_ · · 算法·理论
D1229 抓住那头牛
由于出现了
往队列里放入当前走到了第几格,将使用三种移动方法后所在的格子判断合法后放入队列。
注意一下边界条件:由于可以从终点的后面转移到终点,走过的格子超过终点可合法,但要
#include<bits/stdc++.h>
using namespace std;
int n,k;
struct kkk{
int x,t;
};
int dx[4]={1,-1,0};
bool vis[200005];
int bfs(){
if(n==k){
return 0;
}queue<kkk> q;
q.push({n,0});
while(!q.empty()){
kkk u=q.front();
q.pop();
dx[2]=u.x;
for(int i=0;i<=2;i++){
int xx=u.x+dx[i];
if(xx>=1&&xx<=k+2&&!vis[xx]){
vis[xx]=1;
q.push({xx,u.t+1});
if(xx==k){
return u.t+1;
}
}
}
}
}
int main(){
cin>>n>>k;
cout<<bfs();
return 0;
}
Lucky Numbers (easy)
“选与不选”问题,可以用深搜来写,但是如果想达到广搜的训练目的的话,还是尝试一下用广搜来写。
其实广搜的“选与不选”问题与深搜很像,都是在
但深搜是到一定位数时才判断,不仅要枚举位数,还要取最小值。
广搜就是每“选与不选”完后直接判断合不合法,无需取最小值,直接输出答案即可。
#include<bits/stdc++.h>
using namespace std;
#define int long long
long long n;
int dx[2]={4,7};
bool check(int x){
int a[10]={};
while(x>0){
a[x%10]++;
x/=10;
}return a[4]==a[7];
}
int bfs(){
queue<int> q;
q.push(4);
q.push(7);
while(!q.empty()){
int u=q.front();
q.pop();
for(int i=0;i<=1;i++){
int xx=u*10+dx[i];
q.push(xx);
if(check(xx)){
if(xx>=n){
return xx;
}
}
}
}return 114514;
}
signed main(){
cin>>n;
cout<<bfs();
return 0;
}
Water The Garden
这一题先往队列里放入水龙头所在的位置,每过一秒,就将所有浇过水的格子向左右两边扩展一格,直到所有的水都被浇灌过,队列为空,直退出循环。