这道题已经做了好多遍了,昨天下午做的时候一样的代码在c++上交是re了,在g++上交的时候就wa了,而且有重新打了一个一模一样的,然后就过了,真的是一抹一样的代码,现在还郁闷。这道题的解题思路就是利用广搜把每个点的跳的下一个点的情况都枚举出来,这样找他的最短时间,当然,先出来的就是最短的时间。这道题我收获最大的是队列里的数据不随你刚开始赋值于它的变量的变化而变化,他就是一个常值。
<pre name="code" class="html">#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
int Star, End;
int v[200001];
struct node
{
int step, s;
};
int bfs(int a, int b)
{
queue<node>q;
struct node p,x,tmp;
p.s=a;
p.step=0;
memset(v,0,sizeof(v));
v[a]=1;
q.push(p);
while(!q.empty())
{
x = q.front();
q.pop();
if(x.s == b)
{
return x.step ;
}
if(x.s <= b && !v[x.s + 1])
{
v[x.s + 1] = 1;
p.s = x.s + 1;
p.step = x.step + 1;
q.push(p);
}
if(x.s >= 1 && !v[x.s - 1]) //要保证减1后有意义,所以要X >= 1
{
v[x.s - 1] = 1;
p.s = x.s - 1;
p.step = x.step + 1;
q.push(p);
}
if(x.s <= b && !v[x.s * 2])
{
///node temp;
v[x.s * 2] = 1;
p.s = 2 * x.s;
p.step = x.step + 1;
q.push(p);
}
}
}
int main()
{
while(scanf("%d%d",&Star,&End)!=EOF)
{
int ans=bfs(Star,End);
printf("%d\n",ans);
}
}