某些测试用例未通过

Some test cases aren't passing

本文关键字:测试用例      更新时间:2023-10-16
#include <iostream>
#include <vector>
int i=0;  //points at the current stack that we are working with
int box=0; //no. of boxes held by the crane
int64_t H; //max. height of the stacks given in the que.

int main()
{
int n, value; //storing no. of stacks and creating an additional variable value to store operations
std::cin>> n >> H;
int64_t arr[n]; //storing the no. of boxes each stack has in an array
std::vector<int> arr2;  //storing the operations we have to perform in a vector

for(int j=0; j<n; j++){std::cin>> arr[j];} //getting arr
while(std::cin>>value) //getting arr2
{
arr2.push_back(value);
}

for(int xy=0; xy<n; xy++){if(arr[xy]>H){return 0;}} //ensuring that all stacks have no.of boxes less than max. height 
if(arr2.size()<1 || arr2.size()>10e5 ||  n<1 || n>10e5 || H<1 || H>10e8){return 0;} //constraints given in the que.
int k=0; //creating a variable to keep count of how many programs we have already executed
while(k<arr2.size()){
if(arr2[k] == 1){MoveLeft();}
else if(arr2[k]==2){MoveRight(n);}
else if(arr2[k]==3){PickBox(arr, i);}
else if(arr2[k]==4){Dropbox(arr, i);}
else if(arr2[k]==0){k=arr2.size();}
k++;
}
for(int j=0; j<n; j++){std::cout<< arr[j] << " ";} //printing the arr after executing the code
return 0;
}

这是过去一年ZCO的问题。上面的代码是我为解决问题而编写的。

四个功能Moveleft,MoveRight,Pickbox,Dropbox已在同一文件中定义,但此处未显示,因为我认为它们没有问题。

当我提交代码时,除了 2 个测试用例外,所有测试用例都通过了。我不知道我的代码有什么问题。请帮助我。

我已经尽力使代码可读。抱歉,如果代码看起来很乱。

不幸的是,使用您尝试定义具有用户输入长度的数组的方法在C++中无效。

但幸运的是,基本上有两种方法用于动态分配数组。

方法 1:使用矢量

矢量是C++的重要组成部分。它有很多功能(例如,它的大小不需要像普通数组那样定义静态,可以重新定义数组大小等(举个例子:

#include <iostream>
#include <vector>
int main(void) {
std::vector<int> vArray; // vector<> declaration
int size = 0;
int getInput = 0;
std::cout << "Enter an array size: ";
std::cin >> size;
for (int i = 0; i < size; i++) {
std::cout << "Enter a value: ";
std::cin >> getInput;
vArray.push_back(getInput); // inserts one+ container and data in it
}
for (int i = 0; i < vArray.size(); i++) {
// retrieving contained data...
std::cout << vArray[i] << std::endl;
}
return 0;
}

方法 2:将"new"关键字与指向变量一起使用

简单使用new将帮助您实现您的要求。不太推荐,因为已经有向量的概念,它实际上比数组更有效。让我们看一个简单的程序:

#include <iostream>
int main(void) {
int *pArray;
int size;
std::cout << "Enter an array size: ";
std::cin >> size;
pArray = new int[size]; // initializing array with dynamic size
for (int i = 0; i < size; i++) {
std::cout << "Enter value: ";
std::cin >> pArray[i];
}
for (int i = 0; i < size; i++) {
std::cout << pArray[i] << std::endl;
}
delete[] pArray;
return 0;
}

两者都是不错的选择,但大多数使用vector<>推荐它。