CF1661B Getting Zero

Getting Zero

题面翻译

给定 \(v\),可以将 \(v\) 如下操作:

变成 \((v + 1) \% 32768\) 或者 \(2\times v\%32768\)

求最少经过几次操作能将 \(v\) 变回 \(0\)

题目描述

Suppose you have an integer $ v $ . In one operation, you can:

  • either set $ v = (v + 1) \bmod 32768 $
  • or set $ v = (2 \cdot v) \bmod 32768 $ .

You are given $ n $ integers $ a_1, a_2, \dots, a_n $ . What is the minimum number of operations you need to make each $ a_i $ equal to $ 0 $ ?

输入格式

The first line contains the single integer $ n $ ( $ 1 \le n \le 32768 $ ) — the number of integers.

The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 0 \le a_i < 32768 $ ).

输出格式

Print $ n $ integers. The $ i $ -th integer should be equal to the minimum number of operations required to make $ a_i $ equal to $ 0 $ .

样例 #1

样例输入 #1

4
19 32764 10240 49

样例输出 #1

14 4 4 15

提示

Let's consider each $ a_i $ :

  • $ a_1 = 19 $ . You can, firstly, increase it by one to get $ 20 $ and then multiply it by two $ 13 $ times. You'll get $ 0 $ in $ 1 + 13 = 14 $ steps.
  • $ a_2 = 32764 $ . You can increase it by one $ 4 $ times: $ 32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0 $ .
  • $ a_3 = 10240 $ . You can multiply it by two $ 4 $ times: $ 10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0 $ .
  • $ a_4 = 49 $ . You can multiply it by two $ 15 $ times.

思路

32768实际上是2的15次方。看到最少次数的时候,可以想到bfs宽搜到最短路的性质,而两种操作方式对应的就是扩展方法,依次,我们就能求出来扩展的最少次数。

代码

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int dist[65537];
int bfs(int u){
    memset(dist,-1,sizeof dist);
    queue<int> q;
    q.push(u);
    dist[u]=0;
    while(q.size()){
        int t=q.front();
        q.pop();
        if(!t) return dist[0];
        int f1=(t+1)%32768,f2=(t<<1)%32768;
        if(!~dist[f1]&&dist[t]+1<=15){
            dist[f1]=dist[t]+1;
            q.push(f1);
        }
        if(!~dist[f2]&&dist[t]+1<=15){
            dist[f2]=dist[t]+1;
            q.push(f2);
        }
    }
}
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        bfs(x);
        cout<<dist[0]<<" ";
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值