33,008
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
#define QSIZE 200000
int whereinqueue[QSIZE]; //index of element in queue, -1 if not in queue
int q[QSIZE],qstart,qend; //this is a circular array queue
int dist[QSIZE]; //dist[x] = distance to x from starting position
int n,k;
/*update x in queue, or add if not already in queue and dist==-1*/
void update(int x, int d)
{
if (whereinqueue[x]==-1 && dist[x]==-1)
{
dist[x]=d;
//add x to the end of queue
q[qend]=x; whereinqueue[x]=qend;
qend++; if (qend==QSIZE) qend=0;
}
}
void processqueue(void) /*process the element at the head of the queue*/
{
int x=q[qstart],d=dist[q[qstart]];
//we need to add all places we can reach to the queue
if (x+1<QSIZE) update(x+1,d+1);
if (x-1>=0) update(x-1,d+1);
if (2*x<QSIZE && x!=0) update(2*x,d+1);
//remove head of queue
whereinqueue[x]=-1;
qstart++; if (qstart==QSIZE) qstart=0;
}
int main(void)
{
int i;
scanf("%i %i",&n,&k);
for (i=0;i<QSIZE;i++)
{
whereinqueue[i]=-1;
dist[i]=-1;
}
q[0]=n;
dist[n]=0;
qstart=0;
qend=1; //start at point n
while(qstart!=qend)
processqueue();
printf("%i\n",dist[k]);
return 0;
}
#include<iostream>
#include<queue>
using namespace std;
int a,b,f[200001]={0};
struct node
{int n,s;}t;
int bfs()
{
queue<node> q;
node st={a,0};
q.push(st);
f[a]=1;
while(!q.empty())
{
t=q.front();
if(t.n==b)
return t.s;
q.pop();
node ct={t.n,t.s+1};
if(t.n<b&&!f[2*t.n])
{
f[2*t.n]=1;
ct.n=2*t.n;
q.push(ct);
}
if(!f[t.n+1])
{
f[t.n+1]=1;
ct.n=t.n+1;
q.push(ct);
}
if(t.n-1>=0&&!f[t.n-1])
{
f[t.n-1]=1;
ct.n=t.n-1;
q.push(ct);
}
}
return 0;
}
int main()
{
scanf("%d%d",&a,&b);
printf("%d\n",bfs());
}
private static int step(int x, int y)
{
int value = 0;
for (int y2, y0 = 0; x != y; value++)
{
y2 = y >> 1;
if (--y != x)
{
if ((y & 1) == 0)
{
value++;
if (x < y2)
{
if ((y0 = (y2 & 1)) == 0) y = y2;
else if (x == y2 - 1)
{
value++;
x = y;
}
else y = y2 + 1;
}
else
{
if (x != y2) value += Math.Min(y - x, x - y2) - 1;
x = y;
}
}
else if (x < y2)
{
y0 = 0;
y = y2;
}
else
{
value += Math.Min(y - x - y0, x - y2);
x = y;
}
}
}
return value;
}