joj2431

来源:互联网 发布:云计算是什么意思 编辑:程序博客网 时间:2024/06/02 10:50

 2431: Shift and Increment


Result TIME LimitMEMORY Limit Run TimesAC Times JUDGE
5s 16384K1304 209Standard
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;
}