51,712
社区成员




#include <iostream>
using namespace std;
/** Getting Zero
* either set v=(v+1) mod 32768
* or set v=(2*v) mod 32768
* 输入:第一行输入n - 表示有n个整数;
* 第二行 - 输入n个整数
* 使ai等价于0的最少步骤
*/
int n; //输入n个整数
int a[32778]; //储存整数的数组
/**< 考虑使用bfs或dfs 秉承能用b不用d的原则先试试bfs */
struct node{ //新建队列
int data;
};
int bfs(int ai)
{
struct node que[32778];
int book[32778] = {};
int head = 1,tail = 1; //首、尾指针
que[tail++].data = ai; //将需要处理的原数字入队
book[ai] = 1;
while(head < tail)
{
int x = que[head].data;
int new_x1 = (x+1) % 32768; //第一种每次加1
int new_x2 = (2*x) % 32768; //第二种每次乘2
if(!x)
break;
if(!book[new_x1])
{
que[tail++].data = new_x1;
book[new_x1] = book[x] + 1;
}
if(!book[new_x2])
{
que[tail++].data = new_x2;
book[new_x2] = book[x] + 1;
}
head++;
}
return book[0] - 1;
}
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
{
cin >> a[i];
cout << bfs(a[i]) << " ";
}
return 0;
}