news 2026/3/4 8:09:39

华为OD机试双机位C卷 - 魔法收积木 (C++ Python JAVA JS GO)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
华为OD机试双机位C卷 - 魔法收积木 (C++ Python JAVA JS GO)

魔法收积木

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)}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/27 22:44:18

C++函数与string对象、array对象及递归详解

C函数与string对象、array对象及递归详解 一、string对象的数组操作 string对象比C风格字符串更灵活&#xff0c;可以像结构体一样进行赋值和传递。以下示例展示了string数组的用法&#xff1a; #include <iostream> #include <string> using namespace std;const …

作者头像 李华
网站建设 2026/3/3 4:52:26

Miniconda-Python3.9环境下实现PyTorch模型冷启动优化

Miniconda-Python3.9环境下实现PyTorch模型冷启动优化 在部署深度学习服务时&#xff0c;你是否遇到过这样的场景&#xff1a;系统重启后第一个用户请求响应特别慢&#xff0c;甚至超时&#xff1f;日志显示&#xff0c;并非代码逻辑问题&#xff0c;而是模型加载、依赖初始化等…

作者头像 李华
网站建设 2026/3/1 12:30:53

硬核对决:TruthfulRAG如何运用知识图谱化解RAG知识冲突?

&#x1f4cc; RAG系统的困境 问题的根源&#xff1a;知识冲突 RAG&#xff08;检索增强生成&#xff09;系统中&#xff1a;当外部检索到的知识与模型内部参数化知识不一致时&#xff0c;LLM往往会陷入不知所措。 知识冲突示意图 Figure 1: 知识冲突示意图。现有方法在toke…

作者头像 李华
网站建设 2026/3/4 7:18:14

SpringBoot代码集

一、获取Spring容器对象1.1 实现BeanFactoryAware接口实现BeanFactoryAware接口&#xff0c;然后重写setBeanFactory方法&#xff0c;就能从该方法中获取到Spring容器对象。Service public class PersonService implements BeanFactoryAware {private BeanFactory beanFactory;…

作者头像 李华
网站建设 2026/3/4 6:58:19

2025最新!8个AI论文平台测评:本科生写论文还能这么快?

2025最新&#xff01;8个AI论文平台测评&#xff1a;本科生写论文还能这么快&#xff1f; 2025年AI论文平台测评&#xff1a;为何需要这份榜单&#xff1f; 随着人工智能技术的不断进步&#xff0c;越来越多的本科生开始借助AI工具提升论文写作效率。然而&#xff0c;面对市场上…

作者头像 李华
网站建设 2026/2/28 16:42:09

PyTorch Federated Learning项目环境搭建:Miniconda-Python3.9实测

PyTorch Federated Learning项目环境搭建&#xff1a;Miniconda-Python3.9实测 在联邦学习研究中&#xff0c;最让人头疼的往往不是模型收敛问题&#xff0c;而是“在我机器上明明能跑”的环境灾难。你有没有经历过这样的场景&#xff1a;论文复现时突然报错 ImportError: can…

作者头像 李华