谈判(贪心算法)

题目
谈判(贪心算法)_第1张图片

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();
	}
}

你可能感兴趣的:(蓝桥杯省赛(Java组),java,开发语言)