【华为OD】2024D卷——停车场车辆统计

复制代码
题目描述:
特定大小的停车场,数组cars[]表示,其中1表示有车,0表示没车。
车辆大小不一,小车占一个车位(长度1),货车占两个车位(长度2),卡车占三个车位(长度3),
统计停车场最少可以停多少辆车,返回具体的数目。

输入描述:
整型字符串Q数组cars[],其中1表示有车,0表示没车,数组长度小于1000。
输出描述:
整型数字字符串,表示最少停车数目。

补充说明:
示例1
输入:
1,0,1
输出: 2
说明:
1个小车占第1个车位第二个车位空
1个小车占第3个车位最少有两辆车

示例2
输入:
1,1,0,0,1,1,1,0,1
输出:
3
说明:
1个货车占第1、2个车位第3、4个车位空
1个卡车占第5、6、7个车位第8个车位空
1个小车占第9个车位最少3辆车

解题思路:

使用贪心策略:遇到车位 = 1时,尝试停放卡车;不行再停放货车;再不行停放小车,即可得最少停放数量


代码部分

python 复制代码
def count_car(nums):
    ncount = 0
    length = len(nums)
    i = 0
    while i < length:
        if nums[i] == 1:
            tmp = 1
            while i + 1 < length and nums[i + 1] == 1:  #统计连续为1车位
                tmp += 1
                i += 1
            ncount += tmp // 3   #先停放卡车
            ncount += (tmp % 3) // 2     #再停放货车
            ncount += (tmp % 3) % 2     #再停放小车
            i += 1
        else:   #直接跳过0车位
            i += 1
    return ncount
nums = list(map(int, input().split(',')))
print(count_car(nums))

换一种更容易懂的写法

python 复制代码
    while i < length:
        if nums[i] == 1:
            if i + 2 < len(nums) and nums[i + 1] == 0 and nums[i + 2] == 0:
                # 停放卡车  
                nums[i + 2] = 1
                nums[i + 1] = 1
                nums[i] = 1
                ncount += 1
                i += 3
            elif i + 1 < len(nums) and nums[i + 1] == 0:
                # 停放货车  
                nums[i + 1] = 1
                nums[i] = 1
                ncount += 1
                i += 2
            else:
                # 停放小车  
                nums[i] = 1
                ncount += 1
                i += 1
        else:
            i += 1

知识点:逻辑、贪心


结语:越简单的题目解法应该越多,请路过大神留下新的思路供本小白学习一下,打开思路

相关推荐
孟健2 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞4 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽6 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程11 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪11 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook11 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python