编辑代码

import java.util.ArrayList;  
import java.util.Collections;  
import java.util.List;  
  
public class TourOptimization {  
    public static void main(String[] args) {  
        List<Place> places = new ArrayList<>();  
        places.add(new Place("故宫", 1, 7));  
        places.add(new Place("颐和园", 2, 8));  
        places.add(new Place("长城", 3, 9));  
        places.add(new Place("天坛", 1, 6));  
  
        Collections.sort(places, (a, b) -> b.getScore() - a.getScore()); // 按评分从高到低排序  
  
        int totalValue = 0;  
        List<Place> selectedPlaces = new ArrayList<>();  
        for (Place place : places) {  
            if (place.getDays() + selectedPlaces.stream().mapToInt(Place::getDays).sum() <= 4) {  
                selectedPlaces.add(place);  
                totalValue += place.getScore();  
            } else {  
                break; // 如果已经选择的景点总游览时间超过了4天,则跳出循环  
            }  
        }  
  
        System.out.println("选择的景点:");  
        for (Place place : selectedPlaces) {  
            System.out.println(place.getName() + " - " + place.getScore());  
        }  
        System.out.println("总价值:" + totalValue);  
    }  
}  
  
class Place implements Comparable<Place> {  
    private String name;  
    private int days;  
    private int score;  
  
    public Place(String name, int days, int score) {  
        this.name = name;  
        this.days = days;  
        this.score = score;  
    }  
  
    public String getName() {  
        return name;  
    }  
  
    public int getDays() {  
        return days;  
    }  
  
    public int getScore() {  
        return score;  
    }  
  
    @Override  
    public int compareTo(Place other) {  
        return other.score - this.score; // 按评分从高到低排序  
    }  
}