我已经修改了以下代码,用于进行示例测试 https://www.testdome.com/for-developers/solve-question/9930
"通过从左侧和右侧安装和拆卸货车来构建TrainComposition。 例如,如果我们首先从左侧安装货车7,然后再从左侧安装货车13,我们得到两辆货车的组合(从左到右为13和7)。现在可以从右侧拆卸的第一辆货车是7号,第一辆可以从左侧拆卸的货车是13号。 实现一个模拟这个问题的TrainComposition。"
#include <stdexcept>
#include <iostream>
#include <vector>
class TrainComposition
{
//std::vector<int> wagons;
public:
std::vector<int> wagons;
void attachWagonFromLeft(int wagonId)
{
wagons.insert(wagons.begin(), wagonId);
}
void attachWagonFromRight(int wagonId)
{
wagons.push_back(wagonId);
}
int detachWagonFromLeft()
{
int ret = wagons[0];
wagons.erase(wagons.begin());
return ret;
}
int detachWagonFromRight()
{
int ret = wagons[(int)(wagons.size()) - 1];
wagons.pop_back();
return ret;
}
};
#ifndef RunTests
int main()
{
TrainComposition tree;
tree.attachWagonFromLeft(7);
tree.attachWagonFromLeft(13);
std::cout << tree.detachWagonFromRight() << "\n"; // 7
std::cout << tree.detachWagonFromLeft() << "\n";; // 13
return 0;
}
#endif
测试结果有一个失败 大量货车的性能测试:超出时间限制
请帮助修复此失败......
答案 0 :(得分:0)
这是我解决此问题的示例代码:
#include <stdexcept>
#include <iostream>
#include <deque>
class TrainComposition
{
public:
std::deque<int> my_train;
void showdq()
{
std::deque <int> :: iterator it;
for (it = my_train.begin(); it != my_train.end(); ++it)
std::cout << '\t' << *it;
std::cout << '\n';
}
void attachWagonFromLeft(int wagonId)
{
//std::cout << "Attaching Wagon " << wagonId << " from left!"<< std::endl;
my_train.push_front(wagonId);
}
void attachWagonFromRight(int wagonId)
{
//std::cout << "Attaching Wagon " << wagonId << " from right!"<< std::endl;
my_train.push_back(wagonId);
}
int detachWagonFromLeft()
{
int detachedWagon = my_train.front();
my_train.pop_front();
return detachedWagon;
}
int detachWagonFromRight()
{
int detachedWagon = my_train.back();
my_train.pop_back();
return detachedWagon;
}
};
#ifndef RunTests
int main()
{
TrainComposition tree;
//tree.attachWagonFromLeft(1);
//tree.attachWagonFromLeft(2);
tree.attachWagonFromLeft(7);
tree.attachWagonFromLeft(13);
//std::cout << "Train's Wagon: ";
//tree.showdq();
std::cout << "Detaching " << tree.detachWagonFromRight() << " from right\n"; // 7
std::cout << "Detaching "<< tree.detachWagonFromLeft() << " frim left\n"; // 13
//std::cout << "Train's Wagon After: ";
//tree.showdq();
}
#endif
这是我得到的结果:
Compilation OK
Detaching 7 from right
Detaching 13 frim left
Your score is 100%, perfect!
请注意,使用std::cout
(上面的注释)进行打印会导致以下结果:
Performance test with a large number of wagons: Time limit exceeded
Your score is 67%, nice!