华为OD机试- 空栈压数-2024年OD统一考试(E卷)
C++代码
//模仿stack 先进后出 void Push(std::vector<int>& vect, int num) { if (vect.empty()) { vect.push_back(num); return; } int end = vect[vect.size() - 1]; if (end == num) { vect.erase(std::next(vect.end(),-1)); Push(vect, num * 2); } else { if (vect.size() == 1) { vect.push_back(num); return; } if (vect.size() > 1) { int sum = 0; int i = vect.size() - 1; for (; i >= 0; i--) { sum = sum + vect[i]; if (sum == num) break; } if (i == -1) { vect.push_back(num); return; } else { int forNum = vect.size() - i; for (int k = 1; k <= forNum; k++) { vect.erase(std::next(vect.end(), -1)); } Push(vect, num * 2); } } } } void StackNum(std::vector<int>& vect) { std::vector<int> stk; for (int i : vect) { Push(stk, i); } std::reverse(stk.begin(), stk.end()); for (int i : stk) { std::cout << i << std::endl; } } void main() { std::vector<int> vect{ 5,10,20,50,85,1 }; //StackNum(vect); //Test(); }
void Test() { std::cout << "---------test1-------------" << std::endl; //test1 std::vector<int> vect1{ 80,80,160 }; std::vector<int> stk1; for (int i : vect1) { Push(stk1, i); } std::reverse(stk1.begin(), stk1.end()); for (int i : stk1) { std::cout << i << std::endl; } std::cout << "---------test2-------------" << std::endl; //test2 std::vector<int> vect2{ 1,2,4,4,6 }; std::vector<int> stk2; for (int i : vect2) { Push(stk2, i); } std::reverse(stk2.begin(), stk2.end()); for (int i : stk2) { std::cout << i << std::endl; } std::cout << "---------test3-------------" << std::endl; //test3 std::vector<int> vect3{ 1,3,10,20,50,80,1,1 }; std::vector<int> stk3; for (int i : vect3) { Push(stk3, i); } std::reverse(stk3.begin(), stk3.end()); for (int i : stk3) { std::cout << i << std::endl; } std::cout << "---------test4-------------" << std::endl; //test4 std::vector<int> vect4{ 10,20,50,80,1,1 }; std::vector<int> stk4; for (int i : vect4) { Push(stk4, i); } std::reverse(stk4.begin(), stk4.end()); for (int i : stk4) { std::cout << i << std::endl; } std::cout << "---------test5-------------" << std::endl; //test5 std::vector<int> vect5{ 5,10,20,50,85,1 }; std::vector<int> stk5; for (int i : vect5) { Push(stk5, i); } std::reverse(stk5.begin(), stk5.end()); for (int i : stk5) { std::cout << i << std::endl; } }
结果截图
华为OD2024 E 文章被收录于专栏
实时更新华为2024 E卷答案