F - Catch That Cow-BFS-只计次不求路径

来源:互联网 发布:管家婆普及版数据恢复 编辑:程序博客网 时间:2024/05/22 01:35
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
queue <int> qq;


int track[100010];
int n;


int k;


bool vis[100010];


int bfs()
{

while ( !qq.empty() )
{

int nn=qq.front();

qq.pop();          //获取头后即可剔除;
if (nn==k)  return 0;  

 
if (nn-1>=0 && nn-1<=100010)            //注意如果得到负数 则访问下表为负数的数组会造成RE
{
if (vis[nn-1]==false )
{
qq.push(nn-1); 
vis[nn-1]=true;
track[nn-1]=track[nn]+1;                   //不用溯源法记录父节点,而是用父节点的次数+1,,不用递归求解;空间消耗不变,时间减少
}
}
if (nn+1>=0 && nn+1<=100010) 
{
if (vis[nn+1]==false ) 
{
qq.push(nn+1);
 
vis[nn+1]=true; 
track[nn+1]=track[nn]+1;
}





if (nn*2>=0 && nn*2<=100010) 
{
if (vis[nn*2]==false)   {qq.push(2*nn);vis[nn*2]=true;track[nn*2]=track[nn]+1;}

}




}


return 0;
}
 


int main()
{

scanf("%d%d",&n,&k);
     vis[n]=true;


qq.push(n);



if(n>=k) {printf("%d\n",n-k);return 0;}
else {


bfs();



// output(kk);//



printf("%d\n",track[k]);


}





return 0;

}
0 0
原创粉丝点击