- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
您有一个数组,按“停机时间成本”表示一行服务器。您只能访问线路两端的服务器(即您只能访问第一个 服务器或最后一个 服务器)。
选择服务器的顺序乘以它的停机时间并添加到“总停机时间成本”。
设计一个程序来找到最少的总停机成本。
例如,对于数组:
[5, 3, 6, 2, 1, 4]
最少的总停机时间是:
5*1 + 4*2 + 3*3 + 6*4 + 2*5 + 1*6 = 62
这是我用来获取此结果的代码:
public static void main(String[] args){
int[] serverDowntimes = {5, 3, 6, 2, 1, 4};
int start = 0;
int end = serverDowntimes.length - 1;
long totalCost = 0;
int serverNumber = 1;
while(start <= end){
if(serverDowntimes[start] >= serverDowntimes[end]){
totalCost += serverNumber * serverDowntimes[start];
start++; //Increment start (i.e. First server in line was recovered)
}else{
totalCost += serverNumber * serverDowntimes[end];
end--; //Decrement end (i.e. Last server in line was recovered)
}
serverNumber++;
}
System.out.println(totalCost);
}
但是当我有这个数组时我的代码失败了:
[5, 3, 1, 8, 2, 4]
对于这个数组,我的代码输出:
76 (5*1 + 4*2 + 3*3 + 2*4 + 8*5 + 1*6)
但是更好的答案应该是:
73 (4*1 + 2*2 + 8*3 + 5*4 + 3*5 + 1*6)
如何修改我的代码,使其也适用于类似于以下的数组:
[5, 3, 1, 8, 2, 4]
最佳答案
我编写了蛮力算法来测试所有可能的解决方案并选择最佳解决方案。
对于以下问题集:
[5, 3, 1, 8, 2, 4]
它生成以下解决方案:
最低成本:72,组合:[5, 4, 2, 8, 3, 1]
我们可以通过计算证明:
5*1 + 4*2 + 2*3 + 8*4 + 3*5 + 1*6 = 72
这是求解器:
import java.util.*;
class ServersProblemSolver {
public static void main(String[] args) {
int[] serverDowntimes = {5, 3, 1, 8, 2, 4};
int totalCost = Integer.MAX_VALUE;
List<Integer> bestCombination = new ArrayList<>();
for (int i = 0; i < Math.pow(2, serverDowntimes.length); i++) {
int temporaryCost = 0;
int combination = i;
int start = 0;
int end = serverDowntimes.length - 1;
List<Integer> temporaryCombination = new ArrayList<>();
for (int k = 0; k < serverDowntimes.length; k++) {
if (combination % 2 == 1) {
temporaryCost += (k + 1) * serverDowntimes[start];
temporaryCombination.add(serverDowntimes[start]);
start++;
} else {
temporaryCost += (k + 1) * serverDowntimes[end];
temporaryCombination.add(serverDowntimes[end]);
end--;
}
combination /= 2;
}
System.out.println("combination " + i + ": " + temporaryCombination + ", cost : " + temporaryCost);
if (temporaryCost < totalCost) {
totalCost = temporaryCost;
bestCombination = temporaryCombination;
} else {
temporaryCombination.clear();
}
}
System.out.println("lowest cost: " + totalCost + ", with combination: " + bestCombination);
}
}
0
和 2 ^ N
之间的每个二进制组合,其中 N
是数组的大小。0
还是1
)从start
或end
选择服务器
101
将占用 start
、end
、start
000
将占用 end
、end
、end
110
将占用 end
、start
、start
关于java - 找到最小的总服务器停机时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461317/
kubectl drain首先是否确保带有replicas=1的Pod在其他某个节点上是健康的? 假设Pod由部署控制,并且Pod确实可以移动到其他节点。 目前,如我所见,它仅从节点逐出(删除Pod)
在上一篇文章 STM8单片机低功耗—等待(Wait)模式实现 中介绍了低功耗模式中的等待(Wait)模式代码实现方法,这篇文章就来演示一下 停机(Halt)模式的代码实现。 停机(Halt)模式的进入
默认情况下,AWS 使用 LATEST更新了最新 lambda 版本的别名,我假设执行以下步骤。 现在,LATEST别名点版本 5。 用户部署新版本的 lambda。 部署新版本时,LATEST别名仍
情况 App Engine Flex 上的自定义运行时(Docker/Node) 当我们自己管理资源时手动扩展到 1 个单个实例(2 cpu/6 gb ram) 配置了活性和就绪检查 正如预期的那样,
我是一名优秀的程序员,十分优秀!