JOJ 2431: Shift and Increment

探讨了如何通过移位和增量操作将任意数值转换至0的方法,限制操作结果在0到n范围内,并提供了一个高效的算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


StatusIn/OutTIME LimitMEMORY LimitSubmit TimesSolved UsersJUDGE TYPE
stdin/stdout5s16384K1099158Standard

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>
int a[1000001];
bool f[1000001];//这么大的数组只能设置为全局变量,不能设置为局部变量
int main()
{
 int x,n,num,cnt,beg,end,y,i;
 while(scanf("%d%d",&x,&n)!=EOF)
 {
  memset(f,0,sizeof(f));
  f[x]=true;
  cnt=0;//标记讨论数的个数
  num=0;//记录需要的次数
  beg=0;//标记搜索的开始
  a[cnt++]=x;
  while(!f[0])
  {
   num++;
   end=cnt;//标记搜索的结束
   for(i=beg;i<end;i++)
   {
    y=a[i]*2;
       if(y>=n) y=y%n;
    if(!f[y])
    {
     a[cnt++]=y;
     f[y]=true;
    }
    y=a[i]+1;
    if(y>=n) y=y%n;
    if(!f[y])
    {
     a[cnt++]=y;
     f[y]=true;
    }
   }
   beg=end;
  }
  printf("%d/n",num);
 }
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值