You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法理解Checkerlog注释,代码本地IDE测试通过但Codeforces测试用例2失败

问题分析与解决

Checkerlog内容翻译

测试用例2:
输入:
3 2
5 5 5
1 2
你的输出:8
预期输出:15

代码错误原因

你的代码逻辑存在根本性错误:不管替换用的b数组元素是否大于原a数组的元素,直接将a的元素替换为b中最大的几个元素。但根据题目要求,每次操作必须将原数换成更大的数,否则替换会导致总和减少,无法达到最大化总和的目标。

比如测试用例2中,b数组的所有元素都小于a数组的元素,此时替换反而会让总和从15降到8,与预期结果不符。

修正后的代码

核心逻辑修改

import java.util.Arrays;
import java.util.Scanner;

public class Whiteboard {
    public static long whiteboard(int[] a, int[] b) {
        Arrays.sort(a); // 将a升序排序,优先处理最小的元素
        Arrays.sort(b); // 将b升序排序,从末尾取最大的元素
        long sum = 0;
        // 先计算原数组总和
        for (int num : a) {
            sum += num;
        }
        int i = 0; // 指向a中当前最小的未替换元素
        int j = b.length - 1; // 指向b中当前最大的未使用元素
        // 仅当b元素大于a元素时才替换,保证总和增加
        while (i < a.length && j >= 0) {
            if (b[j] > a[i]) {
                sum += (b[j] - a[i]);
                i++;
                j--;
            } else {
                // 剩余b元素都更小,无需继续替换
                break;
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int testCases = s.nextInt();
        while (testCases-- > 0) {
            int n = s.nextInt();
            int m = s.nextInt();
            int[] whiteboardA = new int[n];
            int[] whiteboardB = new int[m];
            for (int i = 0; i < n; i++) {
                whiteboardA[i] = s.nextInt();
            }
            for (int i = 0; i < m; i++) {
                whiteboardB[i] = s.nextInt();
            }
            System.out.println(whiteboard(whiteboardA, whiteboardB));
        }
        s.close();
    }
}

逻辑说明

  1. 对a数组升序排序,优先处理最小的元素,这样用最大的b元素替换最小的a元素,能最大化总和的增量。
  2. 对b数组升序排序,从末尾开始取最大的元素进行尝试替换。
  3. 仅当b元素大于a元素时才执行替换,否则直接终止循环(剩余b元素更小,替换无意义)。
  4. 主方法中优化了变量命名,避免与题目中的n/m混淆,同时简化了输入读取逻辑。

内容的提问来源于stack exchange,提问作者Starlove

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:55:29