谈判(贪心算法)

题目

java 复制代码
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();
	}
}
相关推荐
jinyishu_37 分钟前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm38 分钟前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
前端工作日常1 小时前
我学习到的Java类和对象区别
java·后端
前端工作日常1 小时前
我学习到的Java类完整结构
java·后端
什巳1 小时前
JAVA练习309- 二叉树的层序遍历
java·数据结构·算法·leetcode
宠友信息1 小时前
消息序号如何保证即时通讯源码聊天记录稳定加载
java·spring boot·redis·python·mysql·uni-app
圣光SG2 小时前
Java Web入门基础知识笔记
java·前端·笔记
行思理2 小时前
微信支付“商家转账用户确认模式”,新手教程
java·开发语言·微信
麻瓜老宋3 小时前
AI开发C语言应用按步走,表达式计算器calc的第一步,中缀表达式词法分析
c语言·开发语言·atomcode
空中湖3 小时前
Spring AI RAG 完整实战:从零搭建企业知识库问答系统
java·人工智能·spring