您的位置:首页 > 其它

Catch That Cow(poj 3278)

2016-06-29 17:56 369 查看
给定两个整数n和k

通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数

//广搜,a是队列,step记录步数,vis记录哪些数被搜到过
#include<cstdio>
#include<iostream>
#define M 1000010
using namespace std;
int step[M],a[M],vis[M];
int main()
{
int n,m,head=0,tail=1;
scanf("%d%d",&n,&m);
a[1]=n;
vis
=1;
while(head<tail)
{
++head;
int u=a[head];
if(u==m)
{
printf("%d",step[head]);
return 0;
}
if(u-1>=0&&!vis[u-1])
{
a[++tail]=u-1;
step[tail]=step[head]+1;
vis[u-1]=1;
}
if(u+1<1000000&&!vis[u+1])
{
a[++tail]=u+1;
step[tail]=step[head]+1;
vis[u+1]=1;
}
if(u*2<1000000&&!vis[u*2])
{
a[++tail]=u*2;
step[tail]=step[head]+1;
vis[u*2]=1;
}
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: