http://poj.org/problem?id=3278bfs:要注意边界条件啊,这里辉哥一直wa肯定就是这个原因啦,哈哈哈哈哈:
#include<stdio.h>
#include<string.h>
#include<math.h>
int n,k,ans,vis[100005],que[100005];
int bfs()
{
int head,tail,now;
memset(vis,0,sizeof(vis));
head=0;
tail=1;
que[1]=n;
vis[n]=1;
while (head<tail)
{
head++;
now=que[head];
if (now<100000&&!vis[now+1])
{
if (now+1==k)
return vis[now];
tail++;
que[tail]=now+1;
vis[now+1]=vis[now]+1;
}
if (now>=1&&!vis[now-1])
{
if (now-1==k)
return vis[now];
tail++;
que[tail]=now-1;
vis[now-1]=vis[now]+1;
}
if (now>=1&&2*now<=100000&&!vis[2*now])
{
if (2*now==k)
return vis[now];
tail++;
que[tail]=2*now;
vis[2*now]=vis[now]+1;
}
}
}
int main()
{
while (scanf("%d%d",&n,&k)==2)
{
if (k<=n)
ans=n-k;
else
ans=bfs();
printf("%d\n",ans);
}
return 0;
}
变量的使用也要有个好的规范才行,不然总是搞错哈。