我正在尝试使用Greedy算法解决以下问题,但没有得到正确的输出。
以下是示例输入: 20 7 10 4 6 7 6 9 4
以下是模型输出: 217
我的输出是: 343 我的算法作为Java代码段在这里:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Elevate {
public static void main(String[] args) throws FileNotFoundException {
Scanner cin = new Scanner(new FileReader("elevate.in"));
int N, M, Weights, waste;
M = cin.nextInt();
N = cin.nextInt();
ArrayList<Integer> wieghts = new ArrayList<>();
ArrayList<Integer> WT = new ArrayList<>();
int numCase =1;
while(N != 0 && M != 0){
Weights = M;
waste = 0;
for (int i = 0; i < N; i++) {
wieghts.add(cin.nextInt());
}
for (int i = 0; i < N; ) {
if(wieghts.get(i) <= Weights){
Weights -= wieghts.get(i);
i++;
}
else{
//we cannot fit more people
//Start again
WT.add(Weights);
Weights = M;
}
}
for (int i = 0; i < WT.size(); i++) {
waste+= (WT.get(i) * WT.get(i) * WT.get(i));
}
System.out.println(numCase +": "+waste);
M = cin.nextInt();
N = cin.nextInt();
wieghts.clear();
WT.clear();
numCase++;
}
}
}
贪婪是一个错误的选择吗?乘客必须按照相同的到达顺序旅行,所以我有点想尽办法了。
修改 贪婪确实是错误的选择,DP应该解决问题。