编程介的小学生 2019-12-30 17:58 采纳率: 0.2%
浏览 68

Help Bubu 程序写作

Problem Description
Bubu's bookshelf is in a mess! Help him!

There are n books on his bookshelf. We define the mess value to be the number of segments of consecutive equal-height books. For example, if the book heights are 30, 30, 31, 31, 32, the mess value is 3, that of 30, 32, 32, 31 is also 3, but the mess value of 31, 32, 31, 32, 31 is 5 - it's indeed in a mess!

Bubu wants to reduce the mess value as much as possible, but he's a little bit tired, so he decided to take out at most k books, then put them back somewhere in the shelf. Could you help him?

Input
There will be at most 20 test cases. Each case begins with two positive integers n and k (1 <= k <= n <= 100), the total number of books, and the maximum number of books to take out. The next line contains n integers, the heights of each book, from left to right. Each height is an integer between 25 and 32, inclusive. The last test case is followed by n = k = 0, which should not be processed.

Output
For each test case, print the case number and the minimal final mess value. Print a blank line after the output of each test case.

Sample Input
5 2
25 25 32 32 25
5 1
25 26 25 26 25
0 0

Sample Output
Case 1: 2

Case 2: 3

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-27 16:02
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # 读取数据
    n,k=readLines()
    k=int(k)
    n=int(n)
    data=as.integer(readLines())
    
    # 定义一个函数来计算书的平均高度
    def avg_height(data):
        return sum(data)/len(data)
    
    # 定义一个函数来计算书的高度差
    def height_diff(data):
        return max(data) - min(data)
    
    # 定义一个函数来计算书的段数
    def seg_count(data):
        return len(set(data))
    
    # 定义一个函数来计算书的段数和段数差
    def mess_value(data):
        return seg_count(data) - height_diff(data)/seg_count(data)
    
    # 遍历所有的书,找到书段数最大的书
    max_mess=-inf
    for i in range(0,n-k+1):
        mess=mess_value(data[i:i+k])
        if mess>max_mess:
            max_mess=mess
    
    print("Case %d:"%(i+1))
    print(max_mess)
    

    这个程序会读取输入的数据,并计算出书的平均高度、高度差以及书的段数。然后根据这些信息,它会计算出书的段数差(即书的段数减去书的段数差),并返回最小的段数差作为最终的结果。

    注意:这个程序只适用于n<=100的情况,如果n大于100,可能会出现内存溢出的问题。

    评论

报告相同问题?

悬赏问题

  • ¥20 看图片)删除这个自动化录屏脚本就一直报错找不到脚本文件,如何解决?(相关搜索:bat文件)
  • ¥750 关于一道数论方面的问题,求解答!(关键词-数学方法)
  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集