【问题标题】:Task scheduling algorithm任务调度算法
【发布时间】:2021-01-03 12:42:40
【问题描述】:

我该如何解决以下问题?我有使用DP的感觉

给定一个数组的任务复杂度,注意复杂度也是他们需要执行的任务的顺序。约束是每天至少安排一项任务。当天的复杂度是当天最高的任务复杂度。通过优化规划可以实现的总体最小复杂度是多少?

例如,假设有n = 5 任务,其中:

complexity = [1, 5, 3, 2, 4]

测试的长度是days = 2。最好的选择是在第一天执行第一个任务,在第二天执行其余任务。第一天的复杂度是 1,因为这是唯一的任务,第二天的复杂度是 5,因为这是当天最复杂任务的复杂度。因此,答案是1 + 5 = 6

Example 1:
5 -> complexity[] size n = 5
30
10
40
20
50
2 -> Days =2

输出:

80

【问题讨论】:

  • 我无法理解,1 + 5 = 6 在您的示例中如何选择是最佳的,Note that the complexity is also the order of the task they need to be executed,您能澄清一下哪个顺序吗?如果您的意思是按顺序排列的数组,那么我猜是问题所在公式是错误的。
  • @4.Pi.n 不是索引的顺序。这意味着我需要先执行复杂度为 1 的任务,然后是复杂度为 2 的任务,然后是 3... 在第一个示例中。
  • 在你的例子中,为什么你选择1 + 5 = 6,是最优的,为什么不选择1 + 2 = 3,什么是约束意味着这个选择?。
  • 因为这样的描述:“当天的复杂度是当天最高的任务复杂度”。所以第一天完成1,第二天完成,2,3,4,5,所以总复杂度是1+5=6
  • 抱歉,我认为您对订单的看法是正确的。我认为这确实意味着应该根据指标来计划任务。否则,示例 1 的答案应该是 60 而不是 80.@4.Pi.n

标签: algorithm scheduled-tasks dynamic-programming


【解决方案1】:

我认为这是 O(n2),所以不是超级最优,但它有效。它是用 Go 编写的。

package main

import "fmt"

func optimize(tasks []int, days int) int {
    // edge case 1: empty c or days <= 0
    // (this is really for data input validation)
    if len(tasks) == 0 || days <= 0 {
        return 0
    }
    // edge case 2: single day - return max
    if days == 1 {
        max := tasks[0]
        for _, v := range tasks[1:] {
            if v > max {
                max = v
            }
        }
        return max
    }
    // edge case 3: tasks = days
    if days == len(tasks) {
        total := 0
        for _, v := range tasks {
            total += v
        }
        return total
    }
    // all other cases:
    possibilities := []int{}
    i := 0
    max := tasks[0]
    for {
        tasksLeft := len(tasks[i+1:])
        daysLeft := days - 1
        if tasksLeft < daysLeft {
            break
        }
        if tasks[i] > max {
            max = tasks[i]
        }
        possibility := max + optimize(tasks[i+1:], days-1)
        possibilities = append(possibilities, possibility)
        i++
    }
    // minimize
    min := possibilities[0]
    for _, p := range possibilities[1:] {
        if p < min {
            min = p
        }
    }
    return min
}

func main() {
    tasks := []int{1, 5, 3, 2, 4}
    days := 2
    fmt.Println(optimize(tasks, days))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-26
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2012-08-30
    • 2020-11-19
    相关资源
    最近更新 更多