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

C++递归求解Codeforces230A出现读取访问违规及返回值丢失问题

问题根源

  • 递归返回值未传递:你调用duel(s + y, n - 1)时没有将该调用的返回值作为当前函数的返回值返回,导致深层递归返回的YES结果无法向上传递到上层调用,最终函数走到末尾触发未定义行为,这就是你遇到内存访问错误、字符串读取错误的核心原因。
  • 函数分支返回值不全:当count>0的场景下,你的函数没有显式返回任何值,属于C++未定义行为,会出现各种不可预期的运行错误。
  • 逻辑不符合题意:230A题要求必须优先挑战战力更低的敌人才能保证战力增长最优,你没有对敌人数组按战力排序,遇到敌人顺序不对的测试用例会直接判断错误。

修复方案

  1. 首先对输入的敌人数组按战力从小到大排序
  2. 递归调用时直接返回递归结果
  3. 补全所有分支的返回值

修复后的代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

vector<vector<int>> arr;

string duel(int s, int n) {
    if (n == 1) {
        return s > arr[0][0] ? "YES" : "NO";
    }
    // 找当前能打的最弱的敌人
    for (int i = 0; i < arr.size(); i++) {
        if (s > arr[i][0]) {
            int y = arr[i][1];
            arr.erase(arr.begin() + i);
            // 直接返回递归调用的结果
            return duel(s + y, n - 1);
        }
    }
    // 没有能打的敌人直接返回NO
    return "NO";
}

int main()
{
    int s, n, x, y;
    cin >> s >> n;
    for (int i = 0; i < n; i++) {
        cin >> x >> y;
        arr.push_back({ x, y });
    }
    // 按敌人战力从小到大排序
    sort(arr.begin(), arr.end());
    cout << duel(s, n);
    return 0;
}

额外说明

你之前加末尾return "NO"所有用例都返回NO的原因就是,递归的结果没有被传递,所有上层调用最后都会走到末尾的返回语句,直接返回NO。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:36:03