http://poj.org/problem?id=3278额额,bfs嘛,这个数据有点强哈,边界条件要搞清楚才能过呢。。呵呵,不错,bfs:
#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;
}
写代码要严谨才行啊,那些变量名什么一定要搞清楚呢!!!
这里就哉了的。