Array2D SetOfStacks(Array2D ope, int size) { // write code here if (ope.empty()) { return Array2D(); } if (size <= 0) { assert(false); } /** @brief has no bugs, but too complex. */ // stack<Array1D> temp; // Array1D cur_array(size); // int cur_index = -1; // for (int i = 0; i < ope.size(); i++) { // if (ope[i][0] == 1) { // if (cur_index == size - 1) { // temp.push(cur_array); // cur_array = Array1D(size); // cur_index = -1; // } // cur_array[++cur_index] = ope[i][1]; // } else if (ope[i][0] == 2) { // if (cur_index == -1) { // if (temp.empty()) { return Array2D(); } // cur_array = temp.top(); // temp.pop(); // cur_index = size - 1; // } // cur_index--; // } else { return Array2D(); } // } // // Array2D result(temp.size() + 1); // if (cur_index > -1) { // result[temp.size()] = Array1D(&cur_array[0], &cur_array[cur_index] + 1); // } // cur_index = temp.size() - 1; // while(!temp.empty()) { // result[cur_index--] = temp.top(); // temp.pop(); // } /** @todo don't pass all test cases */ Array2D result; Array1D cur_array; for (Array2D::iterator it = ope.begin(); it != ope.end(); ++it) { if ((*it)[0] == 1) { if (cur_array.size() == size) { result.push_back(cur_array); cur_array.clear(); } cur_array.push_back((*it)[1]); } else if ((*it)[0] == 2){ if (cur_array.empty()) { if (result.empty()) { assert(false); } cur_array = result.front(); result.pop_back(); } cur_array.pop_back(); } else { assert(false); } } if (!cur_array.empty()) { result.push_back(cur_array); } return result; }