BISHI40数组取精

求解思路

1.先分别计算序列A和B的总和sumA 和sumB

2.将所有元素按照ai+bia_i +b_iai+bi从大到小排序

3.依次选取排序后的元素,累加子集的A和、B和,直到同时满足超过总和的一半

4.输出选取的元素的原始索引

求解代码

java 复制代码
static class Element {
        int a; // 对应数组A的元素值
        int b; // 对应数组B的元素值
        int index;// 该元素在原数组中的索引(从1开始)

        // 构造方法:初始化a、b、index
        Element(int a, int b, int index) {
            this.a = a;
            this.b = b;
            this.index = index;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        String[] strA = br.readLine().split(" ");
        String[] strB = br.readLine().split(" ");

        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        List<Element> elements = new ArrayList<>();

        long sumA = 0, sumB = 0;

        for (int i = 0; i < n; i++) {
            int a = Integer.parseInt(strA[i]); // 把strA的字符串转成整数
            int b = Integer.parseInt(strB[i]); // 把strB的字符串转成整数
            elements.add(new Element(a, b, i + 1)); // 封装成Element,索引从1开始
            sumA += a; // 累加A的总和
            sumB += b; // 累加B的总和
        }

        Collections.sort(elements, (e1, e2) -> {
            long s1 = (long) e1.a + e1.b;
            long s2 = (long) e2.a + e2.b;

            return Long.compare(s2, s1);// 按a+b从大到小排序
        });

        List<Integer> res = new ArrayList<>();
        long currentA = 0, currentB = 0;

        for (Element e : elements) {
            res.add(e.index); // 把当前元素的索引加入结果
            currentA += e.a; // 累加子集的A和
            currentB += e.b; // 累加子集的B和
            // 检查是否满足条件:子集和超过总和的一半
            if (currentA > sumA / 2 && currentB > sumB / 2) {
                break; // 满足条件则停止选取
            }
        }
        out.println(res.size());

        for (int i = 0; i < res.size(); i++) {
            out.print(res.get(i)+(i == res.size() - 1 ? "" : " "));
        }

        out.flush();
        out.close();
        br.close();
    }
相关推荐
Refrain_zc38 分钟前
Android 音视频通话核心 —— 音频编码(AAC)完整解析
java
xiaoshuaishuai81 小时前
C# AvaloniaUI 资源找不到报错
java·服务器·前端·windows·c#
Xin_ye100861 小时前
C# 零基础到精通教程 - 第十八章:部署与发布——让应用上线
开发语言·c#
我是唐青枫1 小时前
Java JdbcTemplate 实战指南:用 Spring 轻量完成数据库增删改查
java·数据库·spring
思麟呀1 小时前
C++11并发编程:call_once一次性执行+atomic原子类型+CAS无锁编程+自旋锁
linux·开发语言·jvm·c++·windows
Lumbrologist2 小时前
【C++】零基础入门 · 第 13 节:类与对象基础
java·c++·算法
码不停蹄的玄黓2 小时前
Java 生产者-消费者模型详解
java·开发语言·python
爱讲故事的2 小时前
操作系统第一讲复习:为什么学习操作系统,以及操作系统到底在做什么?
linux·开发语言·windows·学习·ubuntu·c#
笨蛋不要掉眼泪2 小时前
Java并发编程:Executors框架类深度解析
java·开发语言·并发
南极企鹅2 小时前
深入理解 MVCC:数据库并发控制的基石
java·数据库·mysql