joj 2431: Shift and Increment

2431: Shift and Increment

Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
5s 16384K 1362 215 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)<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;
}

你可能感兴趣的:(Integer,basic,input,扩展,each,output)