CF1661B Getting Zero

Getting Zero

题面翻译

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

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

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

题目描述

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

  • either set v=(v+1)mod32768
  • or set v=(2v)mod32768 .

You are given n integers a1,a2,,an . What is the minimum number of operations you need to make each ai equal to 0 ?

输入格式

The first line contains the single integer n ( 1n32768 ) — the number of integers.

The second line contains n integers a1,a2,,an ( 0ai<32768 ).

输出格式

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

样例 #1

样例输入 #1

4
19 32764 10240 49

样例输出 #1

14 4 4 15

提示

Let's consider each ai :

  • a1=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.
  • a2=32764 . You can increase it by one 4 times: 327643276532766327670 .
  • a3=10240 . You can multiply it by two 4 times: 10240204808192163840 .
  • a4=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]<<" ";
    }

}

posted @   阿四与你  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
主题色彩