永康网站建设内蒙古网站建设

苏州玉梦文化传媒有限公司 2026/09/09 20:23:50

魔法收积木

2025华为OD机试双机位C卷 - 华为OD上机考试双机位C卷 200分题型

华为OD机试双机位C卷真题目录点击查看: 华为OD机试双机位C卷真题题库目录|机考题库 + 算法考点详解

题目描述

考友反馈题目大意:现在有n堆积木,每堆积木都有正整数数量,魔法一次可以把积木数量一致的积木堆砍半,要求出使用魔法收完积木堆的最少要用多少次魔法。

输入描述

第一行输入n代表积木的堆数

第二行输入:n个正整数,用空格分割,表示每堆积木的个数。

输出描述

输出使用魔法收完积木堆的最少要用多少次魔法。

用例1

输入

4 4 4 4 4

输出

3

用例2

输入

2 3 4

输出

4

题解

思路:贪心

  1. 魔法一次可以把积木数量一致的积木堆砍半,为了让使用魔法次数少,就是尽可能让一次魔法处理尽量多堆的积木。
  2. 基于1,可以推导得到先将最大的值砍半,尽可能让它和小的值一同进行处理
  3. 这道题的基本逻辑就是:
    1. 统计所有积木堆,使用哈希表存储不同大小积木堆的个数,
    2. 每次将积木最多堆数量(x)砍半,使用魔法数量+1,更新哈希表mp[x/2] += mp[x]
    3. 不断重复2的逻辑直到所有堆积木数量都变为0结束。
  4. 根据3的逻辑,主要是跟踪最大积木数量,对于java和C++都有对用的map使用,python、c++和go可以使用优先队列 + map去处理。

c++

#include<iostream> #include<vector> #include<string> #include <utility> #include <sstream> #include<algorithm> #include<cmath> #include<map> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; // 会自动按照key排序 记录不同数量积木数量 map<long, long> mp; for (int i = 0; i < n; i++) { long cnt; cin >> cnt; mp[cnt]++; } // 结果 long ans = 0; while (!mp.empty()) { auto it = prev(mp.end()); long x= it->first; long cnt = it->second; mp.erase(it); ans++; long nextX = x >> 1; if (nextX > 0) { mp[nextX] += cnt; } } cout << ans; return 0; }

JAVA

import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int n = Integer.parseInt(br.readLine().trim()); // TreeMap:有序 map,等价于 C++ map // key:积木数量,value:该数量出现的次数 TreeMap<Long, Long> mp = new TreeMap<>(); st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { long x = Long.parseLong(st.nextToken()); mp.put(x, mp.getOrDefault(x, 0L) + 1); } long ans = 0; while (!mp.isEmpty()) { // 取当前最大 key(等价于 prev(mp.end())) Map.Entry<Long, Long> entry = mp.lastEntry(); long x = entry.getKey(); long cnt = entry.getValue(); mp.pollLastEntry(); // 删除最大 key ans++; long nextX = x >> 1; if (nextX > 0) { mp.put(nextX, mp.getOrDefault(nextX, 0L) + cnt); } } System.out.println(ans); } }

Python

importsysimportheapqfromcollectionsimportCounterdefmain():# 读取全部输入data=sys.stdin.read().strip().split()n=int(data[0])nums=list(map(int,data[1:1+n]))# 统计每种积木数量出现次数cnt=Counter(nums)# 用最大堆模拟取最大 key, python默认是最小堆,所以使用负数heap=[-xforxincnt.keys()]heapq.heapify(heap)ans=0whileheap:x=-heapq.heappop(heap)c=cnt.pop(x)ans+=1nx=x>>1ifnx>0:ifnxnotincnt:heapq.heappush(heap,-nx)cnt[nx]+=cprint(ans)if__name__=="__main__":main()

JavaScript

'use strict';constreadline=require('readline');constrl=readline.createInterface({input:process.stdin,output:process.stdout});letlines=[];rl.on('line',line=>{if(line.trim())lines.push(line.trim());});// 手写最大堆classMaxHeap{constructor(){this.data=[];}size(){returnthis.data.length;}// 插入元素push(val){this.data.push(val);this._siftUp(this.data.length-1);}// 弹出最大元素pop(){if(this.data.length===0)returnnull;consttop=this.data[0];constlast=this.data.pop();if(this.data.length>0){this.data[0]=last;this._siftDown(0);}returntop;}_siftUp(i){while(i>0){constp=Math.floor((i-1)/2);if(this.data[i]<=this.data[p])break;[this.data[i],this.data[p]]=[this.data[p],this.data[i]];i=p;}}_siftDown(i){constn=this.data.length;while(true){letmaxIdx=i;constl=2*i+1,r=2*i+2;if(l<n&&this.data[l]>this.data[maxIdx])maxIdx=l;if(r<n&&this.data[r]>this.data[maxIdx])maxIdx=r;if(maxIdx===i)break;[this.data[i],this.data[maxIdx]]=[this.data[maxIdx],this.data[i]];i=maxIdx;}}}rl.on('close',()=>{letidx=0;constn=Number(lines[idx++]);constnums=lines[idx].split(/s+/).map(Number);// Map: 记录每种积木数量出现的次数constmp=newMap();for(leti=0;i<n;i++){constx=nums[i];mp.set(x,(mp.get(x)||0)+1);}constheap=newMaxHeap();for(constkeyofmp.keys())heap.push(key);letans=0;while(heap.size()>0){// 最大数量个数letx=heap.pop();constcnt=mp.get(x);mp.delete(x);ans++;constnextX=x>>1;if(nextX>0){if(!mp.has(nextX))heap.push(nextX);mp.set(nextX,(mp.get(nextX)||0)+cnt);}}console.log(ans);});

Go

packagemainimport("bufio""container/heap""fmt""os")// 最大堆(int64)typeMaxHeap[]int64func(h MaxHeap)Len()int{returnlen(h)}func(h MaxHeap)Less(i,jint)bool{returnh[i]>h[j]}// 大顶堆func(h MaxHeap)Swap(i,jint){h[i],h[j]=h[j],h[i]}func(h*MaxHeap)Push(xinterface{}){*h=append(*h,x.(int64))}func(h*MaxHeap)Pop()interface{}{old:=*h n:=len(old)x:=old[n-1]*h=old[:n-1]returnx}funcmain(){in:=bufio.NewReader(os.Stdin)varnintfmt.Fscan(in,&n)// 记录不同数量积木数量mp:=make(map[int64]int64)// 最大堆h:=&MaxHeap{}heap.Init(h)fori:=0;i<n;i++{varxint64fmt.Fscan(in,&x)ifmp[x]==0{heap.Push(h,x)}mp[x]++}// 结果varansint64=0forh.Len()>0{// 取最大x:=heap.Pop(h).(int64)ifmp[x]==0{continue}cnt:=mp[x]delete(mp,x)ans++nx:=x>>1ifnx>0{ifmp[nx]==0{heap.Push(h,nx)}mp[nx]+=cnt}}fmt.Println(ans)}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

巴中网站建设莱州网站建设

序章:年初的迷茫 —— 代码与文字的拉扯​两年前,我还是个对着 C++ 指针头疼的编程学习者:白天泡在 IDE 里调试代码,改

2026/06/30 14:00:38

网站建设 企业专注网站建设

SLB绑定多个CosyVoice3 ECS实例的高可用语音服务架构在AI语音技术加速落地的今天,如何将一个高性能但资源密集型的语音合成模型稳定地部署到生产环境,是许多开发者

2026/06/30 12:24:31

烟台网站建设塘沽网站建设

Path of Building PoE2实战指南:7天从菜鸟到精通【免费下载链接】PathOfBuilding-PoE2项目地址: https://gitcode.com/GitHub

2026/06/30 11:24:55

商业网站建设低价网站建设

Node.js文件上传终极指南:body-parser与其他模块的完整集成方案【免费下载链接】body-parserNode.js body parsing middleware项目地址

2026/06/30 12:51:33

建设建设网站的网站建设网

OBS Composite Blur插件终极指南:打造专业级视频模糊特效【免费下载链接】obs-composite-blurA comprehensive blur plugin for

2026/06/30 10:40:21

网站建设计划书西安网站建设公司

脑疾病病理复杂且影响广泛,临床诊断依赖多模态医疗数据但面临数据多样性与复杂性带来的精准诊断挑战。图深度学习(GDL)凭借整合多模态信息、刻画受试者间关系的优势

2026/06/30 12:01:58

网站建设设计西安网站建设公司

Miniconda-Python3.9 如何快速克隆和导出环境在数据科学、AI 研究或工程开发中,你是否经历过这样的场景:花了整整一天时间配置好一个 Python 环境&#

2026/06/30 11:28:55

建设部网站随州网站建设

GetQzonehistory:5分钟学会QQ空间历史说说备份技巧【免费下载链接】GetQzonehistory获取QQ空间发布的历史说说项目地址: https://gitcode.co

2026/06/30 13:23:35

合肥网站建设青岛网站建设公司

Wan2.2-T2V-A14B能否识别并生成特定艺术风格如水彩画在AI内容创作迅速演进的今天,一个核心问题逐渐浮现:当用户输入“请生成一段水彩风格的江南春景视频”时

2026/06/30 13:10:34

手机网站建设网站正在建设中

Kafka-King:5大核心功能让Kafka管理从未如此简单【免费下载链接】Kafka-KingA modern and practical kafka GUI client项目地址:

2026/06/30 12:19:30