gpt4 book ai didi

c++ - 计算 Chef 剩余工作的代码

转载 作者:行者123 更新时间:2023-11-28 00:00:15 24 4
gpt4 key购买 nike

最近在练习 codechef 时遇到了 this问题。

一切顺利,这是一个简单的问题,简单的逻辑,好吧,编写代码只花了不到 10 分钟,它在我的机器上也运行良好,但给出了一个运行时错误(SIGSEGV) 当我尝试在 codechef 中执行它时。

我认为我使用的数组可能存在一些问题,没有帮助,我尝试用 gdb 调试它,它也显示良好,我什至尝试了大约 1000 个左右的大测试用例,它运行良好,那么为什么它在 codechef 中显示运行时错误?

代码如下:

#include <iostream>

int main(){
int testCases;
std::cin >> testCases;
while(testCases--)
{
int jobs,n;
std::cin >> jobs >> n;
int doneJobs[n];
for(int i = 0; i < n; i++)
{
std::cin >> doneJobs[i];
}
bool todoJobs[jobs] = {false};
for(int i = 0; i < n; i++)
{
todoJobs[doneJobs[i] - 1] = true;
}
bool toSkip = false;
for(int i = 0; i < jobs; i++)
{
if(todoJobs[i] == false)
{
if(toSkip == false)
{
std::cout << i + 1 << ' ';
toSkip = true;
todoJobs[i] = true;
}
else
{
toSkip = false;
}
}
}
std::cout << std::endl;
for(int i = 0; i < jobs; i++)
{
if(todoJobs[i] == false)
{
std::cout << i+1 << ' ';
}
}
std::cout << std::endl;
}
return 0;
}

编辑:感谢 @DominiqueLorre 指出输入的一些随机值会导致 Runtime Error ,但我仍然得到它,这里是我编辑的代码:

#include <iostream>

int main(){
int testCases;
std::cin >> testCases;
while(testCases--){
int jobs,n;
std::cin>>jobs>>n;
bool todoJobs[jobs] = {false};
for(int i=0;i<n;i++){
int testJob;
std::cin >> testJob;
todoJobs[testJob-1] = true;
}
bool toSkip = false;
for(int i=0;i<jobs;i++){
if(todoJobs[i] == false){
if(toSkip == false){
std::cout << i+1 << ' ';
toSkip = true;
todoJobs[i] = true;
}else{
toSkip = false;
}
}
}
std::cout << std::endl;
for(int i=0;i<jobs;i++){
if(todoJobs[i] == false){
std::cout << i+1 << ' ';
}
}
std::cout << std::endl;
}
return 0;
}

最佳答案

根据问题定义,声明 n,m 满足 0 ≤ m ≤ n ≤ 1000(在您的代码中 n => jobs, m => n) , 因此测试用例 0 0 是有效的。但是,如果 jobs 为 0,则以下代码片段将导致运行时错误,因为 C++14 不允许声明大小为零的动态数组。

bool todoJobs[jobs] = {false};

在数组分配之前添加语句来检查jobs的值。

if (jobs <= 0) continue;

关于c++ - 计算 Chef 剩余工作的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39608905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com