某些船只受携带的燃料、生活补给等限制,不停靠港口的连续航行距离有 限。假设一艘轮船的最大航程为N,其返航航线上有M个港口,每个港口的停 靠费用存在较大差异,请为该轮船设计一个返航时的最佳停靠方案。如果存在两条费用相同且为最小值的方案,必须选择按照港口序列号字典序较小的 方案。 备注:港口的费用都是>=0的。目的港口不计算在返航航线上。 解答要求 时间限制:C/C++1000ms,其他语言:2000ms内存限制:C/C++256MB,其他语言:512MB 输入 第一行:整数n,代表港口数量,取值范围[15000] 第二行:n个整数,空格隔开,为每个港口的费用值,取值范围[1.1000001] 第三行:n个整数,空格隔开,为每个港口到下一个港口的航程,取值范围[0,100000] 第四行:1个整数,为该船的最大航程 注意: 1、描述的港口不包括返回的目的港口,目的港口的费用也不用考虑。 2、序号为0的港口是出发港口,需要考虑该港口的费用 输出 依次输出轮船停靠港口的索引号,空格隔开(最后一个索引号后也有一个空格):如果无解,输出一个-1。 备注:第一个港口的索引号为0,依次类推。 样例1 输入: 4 2 1 2 3 1 2 4 3 3 输出: -1 解释:航线上有4个港口,最大航程是3,港口的费用为[2 1 2 3],到下一个港口 的距离是[1 2 4 3] 2号港口到下一个港口的距离为4,大于最大航程3,不存在可行返程方案 样例2 输入: 4 1 1 1 1 1 1 1 1 2 输出: 0 2 解释:从0号港口触发,经过航程2,到达2号港口,再经过航程2,到达目的港 口(目的港口不在序列中) 样例3 输入: 5 1 1 1 1 1 1 1 1 1 1 2 输出: 0 1 3 解释:存在两个费用相等且都为最小的方案:(0.2.3)和(0.1.3)。费用都是 3,按照字典序,选择0.1.3为最终方案
使用dfs把所有的路径全部找出来,再比较得到最小花费的路径
public class HuaWei3 {
static List<List<Integer>> res=new LinkedList<>();
static LinkedList<Integer> path=new LinkedList<>();
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] fee=new int[n];
int[] dis=new int[n];
for (int i = 0; i < n; i++) {
fee[i]=sc.nextInt();
}
for (int i = 0; i < n; i++) {
dis[i]=sc.nextInt();
}
int ability=sc.nextInt();
path.push(0);
traverse(fee,dis,0,ability);
int totalFee=Integer.MAX_VALUE;
int index=0;
if(res.size()==0){
System.out.println(-1);
return;
}
Collections.sort(res,(o1,o2)->{
int m1=o1.size();
int m2=o2.size();
if(m1>m2)
return m2-m1;
else if(m1<m2)
return m1-m2;
else{
for (int i = 0; i < m1; i++) {
if(o1.get(i)==o2.get(i))
return o2.get(i)-o1.get(i);
}
return 1;
}
});
for(List<Integer> r:res){
int p=calFee(r,fee);
if(p<totalFee){
index=res.indexOf(r);
totalFee=p;
}
}
for (Integer r:res.get(index)){
System.out.print(r+" ");
}
}
public static void traverse(int[] fee,int[] dis,int cur,int ability){
int s1=0;
for (int i = cur+1; i < dis.length; i++) {
s1+=dis[i];
}
if(s1<ability){
res.add(new LinkedList<>(path));
return;
}
for (int j = cur+1; j < fee.length; j++) {
int s2=0;
for (int k = cur; k <j ; k++) {
s2+=dis[k];
}
if(s2<=ability){
path.add(j);
traverse(fee,dis,j,ability);
path.removeLast();
}
else
break;
}
}
static int calFee(List<Integer> r,int[] fee){
int sum=0;
for (int i = 0; i <r.size() ; i++) {
sum+=fee[r.get(i)];
}
return sum;
}
}