谈判(贪心算法)

时间:2024-01-27 11:59:06
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); List<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { int x = sc.nextInt(); list.add(x); } Collections.sort(list);//1 3 5 9 int sum = 0; while(list.size()!=1) { int a = list.get(0); int b = list.get(1); int c = a+b; sum+=c; list.remove(0);//3 5 9 list.remove(0);//5 9 list.add(c);//5 9 4 Collections.sort(list);//4 5 9 } System.out.println(sum); sc.close(); } }