我有m辆卡车要装载,一辆给定的卡车只在提到的Left[i] to Right[i]天内可用,卡车容量表示为Capacity[i],并收取一些金额表示为Cost[i]

因此每辆卡车有4个参数,天数表示为Left[i] to Right[i] with Capacity[i] and Cost[i]

对于给定的n天作为输入,我需要进行负载的能力k对每一天,找到最低成本运输负载使用卡车.

Example:

n = 5 days
k = 7 capacity per day
trucks = [[1,3,5,2], [1,4,5,3], [2,5,10,1]], each item in the array represents Left, Right, Capacity and Cost

Answer:

44

Explanation:

for trucks[0] = [1,3,5,2] , it is available on days 1 to 3, with truck capacity as 5 and charges 2

I have a task to carry a capacity of k=7 for each day, with number of days as n=5

a) Day 1

Day 1, we have trucks[0] and trucks[1] but lowest cost is for trucks[0] as 2 but it has only capactity as 5

So Day 1, transport 5 items using trucks[0] and 2 items using trucks[1], so cost is 5*2 + 2*3 = 16

b) Day 2, we can pick trucks[2]=[2,5,10,1] because left=2 matches with the day we are looking for also it can carry a capacity of 10 load.

Cost for Day 2 is 7*1 = 7

c) Day 3, pick trucks[2]=[2,5,10,1] because 3 falls in range [2,5], cost for Day 3 is 7*1 = 7
d) Day 4, pick trucks[2]=[2,5,10,1] because 4 falls in range [2,5], cost for Day 3 is 7*1 = 7
e) Day 5, pick trucks[2]=[2,5,10,1] because 5 falls in range [2,5], cost for Day 3 is 7*1 = 7

Total cost for all days is = 16+7+7+7+7 = 44

Constraints:

n and m range is 1 to 10^4
Also we always have enough trucks to carry the load for a particular day

这是我的做法:

Use for loop from 1 to number of days
    Loop through all the trucks and select the trucks that can carry load in the required days and put them in PriorityQueue that is sorted by cost in descending order.
    Next using a loop, poll items from queue, and calculate cost for given day.

我的代码有O(n*m*m)的时间复杂度,如何在更短的时间内解决这个问题?

推荐答案

你的O(n*m²)英镑是从哪里来的?我看到了一辆O(n*m*log(m))

n-times O(n*...)
  sort-by-m O(mlog(m))
  iterate-over-m //O(m), irrelevant, dominated by previous

可能会降到O(n*m+m*log(m))

sort trucks by cost ascending O(m*log(m))
make a int hauled[n] table initialized to zero
int cost=0
for each truck: O(m*...)
  for i from left to right: O(n)
    if hauled[i] < k:
      cost+=truck cost
      hauled[i]+=truck capacity
return cost

Java相关问答推荐

Maven Google Sheets版本问题

如何转换Tue Feb 27 2024 16:35:30 GMT +0800 String至ZonedDateTime类型""

即使我正在使用并发方法,使用Javascript的应用程序也会继续冻结'

GSON期间的Java类型擦除

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

S,要对Java复制构造函数深度克隆所有属性进行单元测试,最可靠的方法是什么?

我的Spring Boot测试显示&IlLegalStateException:无法加载某事的ApplicationContext.

Domino Designer 14中的保存代理添加了重影库

在Java中将int[]矩阵添加到ArrayList中,但出现错误

由于在生成器模式中使用泛型,lambda表达式中的返回类型错误

Java中不兼容的泛型类型

如何以编程方式保存workBench.xmi?

判断重复的两个二维表算法?

如何通过Java java.lang.Foreign API访问本机字节数组

Java HashMap保留所有时间复杂性

Java类型推断:为什么要编译它?

如何判断元素计数并在流的中间抛出异常?

使用DynamoDB增强客户端时未更新属性

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?

如何使用 Java 替换位于特定标记内的 XML 标记的 CDATA 内的值