【发布时间】:2019-02-13 19:16:36
【问题描述】:
问题:
你要去长途旅行。您从 0 英里路段开始上路。沿途有 n 家酒店,编号为 1 ≤ i ≤ n,英里路段 a 1
有谁知道我如何编写一个使用贪心算法来解决这个问题的 Java 代码?
我已经拥有的是:
public static void greedy(int[] a) {
int[] hotel = a;
int[] cost = new int[hotel.length];
int[] stop = new int[hotel.length];
int dist = 0;
for (int i = 0; i < hotel.length - 1; i++) {
dist = a[i + 1] - a[i];
cost[i] = (int) (Math.pow((200 - hotel[i]), 2));
stop[i] = 0;
}
}
但我不知道从这里去哪里..
【问题讨论】:
-
1.从一个具体的例子开始。 2. 手动“执行”示例,记下您执行的每个步骤。 3. 尝试编写代码来执行您手动执行的每个步骤。 4. 继续编写代码,直到它给出与您手动得到的相同的答案。 5. 用更多的例子进行测试。
-
对于解决方案不仅限于
greedy的惊人相似问题,请参阅Long trip, cheap hotels。 -
200 miles是一日游的硬上限吗?