您的位置:首页 > 其它

C - Catch That Cow

2015-07-15 13:40 267 查看
题目大意农民约翰需要抓住他的牛,他和他的牛在一条直线上(估计是一维生物),约翰在NN (0 ≤ N ≤ 100,000)处,他的牛在 K (0 ≤ K ≤ 100,000) ,约翰下次可以移动到x+1或者x-1或者2*x的地方,问约翰最少需要多少步才能找到他的牛。
也是非常非常水的题目,求最快当然是用广搜...
//////////////////////////////////////////////////////////////
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

#define maxn 100001

int v[maxn];//标记是否走过,防止重走

int BFS(int s, int e)
{
queue<int> Q;

Q.push(s);
v[s] = 1;

while(Q.size())
{
s = Q.front();
Q.pop();

if(s == e)
return v[s]-1;

for(int i=0; i<3; i++)
{
int q=s;

if(i == 0)
q--;
else if(i == 1)
q++;
else
q *= 2;

if(q>=0 && q <=maxn && v[q] == 0)
{
Q.push(q);
v[q] = v[s]+1;
}
}
}

return -1;
}

int main()
{
int s, e;

while(scanf("%d%d", &s, &e) != EOF)
{
memset(v, 0, sizeof(v));

int ans = BFS(s, e);

printf("%d\n", ans);
}

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