您的位置:首页 > 其它

joj 2431: Shift and Increment

2011-12-11 17:36 309 查看

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: