joj 2431: Shift and Increment

2431: Shift and Increment


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
5s16384K1362215Standard

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)<x<n) p="" <="" line.="" in="" rules="" above="" the="" under="" 0="" to="" x="" from="" times="" minimal="" ouput="" should="" you="" each="">

Sample Input

2 4
3 9

Sample Output

1
3

Problem Source: provided by skywind

#include<iostream>
#include<cstring>
using namespace std;
int a[1000003];//用来存储每个节点的数
int vis[1000003]={0,1};//用来判断每个节点的数是否被搜过。
int main()
{
 int x,n;
 while(scanf("%d%d",&x,&n)==2)
 {
  memset(vis,0,sizeof(vis));
  if(x>=n)
   x=x%n;
  int beg=0,end=0;//这是广搜中每一层的起点和终点
  int cnt=0,number=1;//cnt用来记录层数,number用来记录所有出现的数字。
  a[0]=x;//第一个数
  vis[x]=1;
 
  while(!vis[0])//vis[0]==1时相当于找到了n
  {
   cnt++;
   beg=end;
      end=number;
   for(int i=beg;i<end;i++)//对每一层的数进行处理
   {
    int k=a[i]*2;
    if(k>=n)
     k=k%n;
    if(!vis[k])//向下一层左扩展
    {
     a[number++]=k;
     vis[k]=1;
    }
    k=a[i]+1;
    if(k>=n)
     k%=n;
    if(!vis[k])//向下一层右扩展
    {
     a[number++]=k;
     vis[k]=1;
    }
   }
   
  }
  printf("%d\n",cnt);
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值