joj2431

 2431: Shift and Increment


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
5s 16384K 1304 209 Standard
Shift and increment is the basic operations of the ALU (Arithmetic Logical Unit) in CPU. One number can be transform to any other number by these operations. Your task is to find the shortest way from x to 0 using the shift (*=2) and increment (+=1) operations. All operations are restricted in 0..n, that is if the result x is greater than n, it should be replace as x%n.


Input and Output


There are two integer x, n (n <=1000000)


Sample Input


2 4
3 9
Sample Output


1
3




#include<cstdio>

#include<cstring>
int visited[1000001];//储存节点是否被访问
int temp[1000001];//储存数据
int main()
{
int x,n;
while(scanf("%d%d",&x,&n)==2)
{
memset(visited,0,sizeof(visited));
int layer=0;//记录访问的次数
int head=0;
int tail=0;
int number=1;
temp[0]=x;
visited[x]=1;
while(!visited[0])
{
head=tail;
tail=number;
layer++;
for(int i=head;i<tail;i++)//对于每一层套从左到又依次遍历
{
int k=temp[i]*2;
if(k>=n)k=k%n;
if(!visited[k])
{
visited[k]=1;
temp[number++]=k;
}
k=temp[i]+1;
if(k>=n)k=k%n;
if(!visited[k])
{
visited[k]=1;
temp[number++]=k;
}
}
}
printf("%d\n",layer);
}
return 0;
}

你可能感兴趣的:(Integer,basic,input,layer,output)