2431: Shift and Increment

2431: Shift and Increment


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
5s16384K1132174Standard

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

 

Problem Source: provided by skywind

#include<iostream>
#include<algorithm>
using namespace std;
const int inf=1000005;
bool flag[inf];
int a[inf];
int main()
{
    int x,n,i;
    while(scanf("%d%d",&x,&n)==2)
    {
        memset(flag,0,sizeof(flag));
        int begin,end,num;
        begin=end=num=0;
        a[num++]=x;
        flag[x]=1;
        int count=0;
        while(flag[0]==0)
        {
            end=num;
            count++;
            for(i=begin;i<end;i++)
            {
                int t=(a[i]*2)%n;
                if(flag[t]==0)
                {
                    flag[t]=1;
                    a[num++]=t;
                }
                t=(a[i]+1)%n;
                if(flag[t]==0)
                {
                    flag[t]=1;
                    a[num++]=t;
                }
            }
            begin=end;
        }
        printf("%d/n",count);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值