点击查看题目
题目大意:
给定两个数n和k, 从n到k有n-1, n+1, 2*n三种操作, 求最少需要几步从n走到k
分析
求最短路径, 用BFS
注意:
- 数组开全局数组, 局部数组可能RE
- 注意剪枝, 不然过不了0, 100000这组数据
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
//全局变量
int n, k, time[1000005], temp;
bool visit[1000005];
queue<int>q;
void bfs()
{
q.push(n);
visit[n]=0;
time[n]=1;
while(!q.empty())
{
temp=q.front();
q.pop();
if(temp==k)
{
return ;
}
if(visit[temp-1] && temp>=1)//剪枝
{
q.push(temp-1);
visit[temp-1]=0;
time[temp-1] = time[temp]+1;
}
if(visit[temp+1] && temp<k)//剪枝
{
q.push(temp+1);
visit[temp+1]=0;
time[temp+1] = time[temp]+1;
}
if(visit[2*temp] && temp<k)//剪枝
{//printf("temp*2=%d\n", temp*2);
q.push(2*temp);
visit[temp*2]=0;
time[temp*2] = time[temp]+1;
}
}
return ;
}
int main()
{
memset(visit, 1, sizeof(visit));
scanf("%d%d", &n, &k);
memset(time, 0, sizeof(time));
bfs();
printf("%d\n", time[k]-1);
return 0;
}