剛看了挑戰程式設計競賽上的搜尋入門專題,做完書上走迷宮的問題正好來做這個不是很難(可能對大佬來說這都不叫題)的題,算是正式做的第二道廣搜題吧,對搜尋已經有了一定的了解,簡單來說就是在現在這個位置,下一步應該往哪邊走,把所有的方向都要列舉出來。
下面是這個題的代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 100010;
int n,k,ans,step[maxn],vis[maxn];
int bfs()
{
int que[maxn],frt = 0,til = 0;
memset(que,0,sizeof(que));
que[til++] = n;
vis[n] = 1;
while(frt != til)
{
int q = que[frt++];
int next;
for(int i = 0;i < 3; i++)
{
if(i == 0)
next = q + 1;
if(i == 1)
next = q - 1;
if(i == 2)
next = 2 * q;
if(next >= 0 && next < maxn && !vis[next])
{
que[til++] = next;
vis[next] = 1;
step[next] = step[q] + 1;
}
if(next == k)
return step[next];
}
}
}
int main()
{
scanf("%d %d",&n,&k);
if(k <= n)
printf("%d",n - k);
else
printf("%d",bfs());
return 0;
}
PS:BFS入門題目,不過做出來也是很開心的,終于會用BFS了。