每日打卡(1/1)
传送门:点击打开链接
题目大意:农夫在位置n,要去位置k。只能去前后两格或者到2*x(x为当前位置)的去,问到k最少要多少步。
由于思维惯性,看见暴力题第一反应是DFS,结果搜了半天搜不出来,其实这是可以预见的,仔细想想就可以知道DFS的上界不好确定,大大加大了搜索的深度。
所以,正确做法就是------------BFS!
一个与二维图不太一样的地方就是,从当前节点到下一节点的过渡,可以用一个for循环来表示。
自然而然地写完了,第一次WA。 原因:没有写vis数组,当n和k距离很大时加大了复杂度。
第二次WA。。原因:没有加上下界,如果越界的话继续搜是没有意义的。
第三次RE。。原因:上界写错了。。
第四次WA。。原因:数组开小了。。
第五次AC,但是1407ms。。原因:上界多打了一个0.。。
第六次正常时间AC,发现scanf确实比cin快了不少。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
#include<queue>
using namespace std;
const int maxn = 1e5+1;
int n,k,ans;
bool vis[maxn+1];
struct node{
int x,tot;
};
int bfs()
{
memset(vis,0,sizeof(vis));
node a;
queue<node> q;
a.x = n;
a.tot = 0;
q.push(a);
while(!q.empty())
{
a = q.front();
if(a.x==k) {
return a.tot;
}
vis[a.x] = 1;
q.pop();
node next;
for(int i=0;i<3;i++)
{
if(!i) next.x = a.x+1;
else if(i==1) next.x = a.x*2;
else next.x = a.x-1;
if(next.x>0&&next.x<maxn&&!vis[next.x]) {
next.tot = a.tot+1;
q.push(next);
}
}
}
return 0;
}
int main()
{
scanf("%d%d",&n,&k);
if(n>=k) {
cout<<n-k<<endl;
return 0;
}
ans = bfs();
cout<<ans<<endl;
return 0;
}