故障的服务器和贪婪算法

发布于 2025-02-02 01:22:15 字数 877 浏览 4 评论 0原文

我目前正在处理的主题称为贪婪算法。有这样的任务

有一个故障的服务器可以在不重新启动的情况下工作 比T分钟。重新启动服务器需要一分钟。 给您提供服务器没有请求的时间列表 以整数的形式一分钟,代表 无需开始时间和当前时间,越来越多地排序。那就是 服务器时仅可能的时间插槽(每个插槽长1分钟) 可以重新启动。 您应该输出服务器工作所需重新启动的最短时间 从现在开始。如果服务器必须在那里重新启动 是发送给它的请求(即不可能将所有重新启动都放入 给定的时间插槽),输出-1插入。

我天真的解决方案看起来,所以

def minRestarts(m, t, no_request_times):
    min_restarts = 0
    rest_times = []
    rt=t
    while t <= m:
        rest_times.append(t)
        t += rt+1
    for i in rest_times:
        if i in no_request_times:
            min_restarts += 1
        else:
            return -1
    return min_restarts

我不确定这里是否有任何贪婪,但它似乎在这样的测试中起作用,例如

m=100
t=20
no_request_times = [50] 

输出-1。但是在另一个测试中,

m=100
t=20
no_request_times = [20,41,62,83]

我有4个作为输出。但这一定是-1?还是我的答案正确?可能是我不了解任务。您能告诉我是否正确。

The topic I am currently working on is called Greedy Algorithms. There is such a task

There is a faulty server that can work without restarting no longer
than t minutes. Restarting a server takes exactly one minute.
You are given a list of times when there will be no requests to the server
for a minute in the form of integers representing difference between
no-request start time and current time, sorted increasingly. So that is the
only possible time slots (each one is 1 minute time long) when the server
can be restarted.
You should output the minimum time of restarts needed for server to work for
m minutes starting from now. If the server would have to restart when there
are requests sent to it (i.e. it is impossible to fit all the restarts into
the given time slots), output -1 insteed.

My naive solution looks so

def minRestarts(m, t, no_request_times):
    min_restarts = 0
    rest_times = []
    rt=t
    while t <= m:
        rest_times.append(t)
        t += rt+1
    for i in rest_times:
        if i in no_request_times:
            min_restarts += 1
        else:
            return -1
    return min_restarts

I'm not sure if there is anything greedy here but it seems to work on such test for example

m=100
t=20
no_request_times = [50] 

It outputs -1. But on the other test

m=100
t=20
no_request_times = [20,41,62,83]

I have 4 as the output. But it must be -1? Or my answer is correct? May be I don't understand the task. Could you please tell me if it is correct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文