pku 3278 Catch That Cow bfs

来源:互联网 发布:淘宝引流工具有用吗 编辑:程序博客网 时间:2024/05/17 11:35

//简单的bfs,注意不要超过  133333,否则“无效内存引用”;

//x*2 - 100000 < x - 100000, 求得 x < 1333333; 为最优的数

//其实不需要,开到200000就行。


#include<stdio.h>

#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
int f[250000];
struct node
{
int pos,time;
};
int t,n,k;


bool vis(int a)
{
if(a>=0 && a<=133333 && f[a]==0)
return true;
return false;
}


int bfs()
{
node sta,next;
int i,j;
sta.pos=n;
sta.time=0;
f[n]=1;
queue<node>q;
q.push(sta);
while(!q.empty())
{
sta=q.front();
q.pop();
if(sta.pos == k)
return sta.time;

for(i=1;i<=3;i++)
{
switch(i)
{
case 1:next.pos =sta.pos+1;break;
case 2:next.pos =sta.pos-1;break;
case 3:next.pos =sta.pos*2;break;
}
if(vis(next.pos))
{
next.time=sta.time+1;
f[next.pos]=1;
q.push(next);
}
}

}
}
int main()
{
int i,j;
scanf("%d",&t);
while(t--)
{
memset(f,0,sizeof(f));
scanf("%d%d",&n,&k);
int sum=bfs();
printf("%d\n",sum);
}
}
原创粉丝点击