为什么这段代码有运行时错误(OutOfBounds);)

问题描述 投票:0回答:1

为什么这段代码有运行时错误(OutOfBounds);)

这是 USACO 2023 年 12 月竞赛,铜牌 1 题

这是问题链接https://www.usaco.org/index.php?page=viewproblem2&cpid=1347#

#include <iostream>
using namespace std;
long long n_h[20009]; // cow height
long long m_h[20009]; // cane height
long long space_h[20009]; // 사탕수수 아래 빈 공간 크기
long long caneat;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    long long n, m; // cow num // cane num
    cin >> n >> m;
    for(int i = 0; i < n; i++){
        cin >> n_h[i];
    }

    for(int i = 0; i < m; i++){
        cin >> m_h[i];
    }

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            if(m_h[i] <= 0){
                break;
            }
            if(m_h[i] + space_h[i] <= n_h[j]){ // 키가 작으면 먹지 못함
                n_h[j] = n_h[j] + m_h[i]; // 소의 키 키우기
                m_h[i] = -1;
                break;
            }
            else{
                if(space_h[i] < n_h[j]){
                    caneat = 0;
                    caneat = n_h[j] - space_h[i];
                    n_h[j] = n_h[j] + caneat;
                    space_h[i] = space_h[i] + caneat;
                    m_h[i] = m_h[i] - caneat;
                }
            }
        }
    }

    for(int i = 0; i < n; i++){
        cout << n_h[i] << "\n";
    }
    return 0;
}
c++ runtime-error indexoutofboundsexception
1个回答
0
投票

您的数组大小为 20,009,比 n,m 的限制 200,000 小。再加一个零就行了

long long n_h[200009]; // cow height
long long m_h[200009]; // cane height
long long space_h[200009]; // 사탕수수 아래 빈 공간 크기
© www.soinside.com 2019 - 2024. All rights reserved.