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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值