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();
    }
相关推荐
枫叶丹418 小时前
【HarmonyOS 6.0】ArkWeb PDF预览回调功能详解:让PDF加载状态可控可感
开发语言·华为·pdf·harmonyos
小陈工18 小时前
数据库Operator开发实战:以PostgreSQL为例
开发语言·数据库·人工智能·python·安全·postgresql·开源
耿雨飞18 小时前
Python 后端开发技术博客专栏 | 第 07 篇 元类与类的创建过程 -- Python 最深层的魔法
开发语言·python
qq_120840937118 小时前
Three.js AnimationMixer 工程实战:骨骼动画、剪辑切换与时间缩放
开发语言·javascript·ecmascript
Dxy123931021618 小时前
Python在图片上画多边形:从简单轮廓到复杂区域标注
开发语言·python
楼田莉子18 小时前
同步/异步日志系统:日志器管理器模块\全局接口\性能测试
linux·服务器·开发语言·c++·后端·设计模式
geNE GENT18 小时前
Spring Boot管理用户数据
java·spring boot·后端
人邮异步社区18 小时前
文科生零基础学 Python 难吗?真不难,难的是找对书!
开发语言·python
怒放吧德德18 小时前
Spring Boot实战:Event事件机制解析与实战
java·spring boot·后端
春栀怡铃声18 小时前
【C++修仙录02】筑基篇:类和对象(上)
开发语言·c++·算法