| Status | In/Out | TIME Limit | MEMORY Limit | Submit Times | Solved Users | JUDGE TYPE |
|---|---|---|---|---|---|---|
| stdin/stdout | 5s | 16384K | 1099 | 158 | 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)
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;
}
探讨了如何通过移位和增量操作将任意数值转换至0的方法,限制操作结果在0到n范围内,并提供了一个高效的算法实现。

152

被折叠的 条评论
为什么被折叠?



