Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
205 views22 pages

Stack - Attempt Review

Uploaded by

Jo Ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
205 views22 pages

Stack - Attempt Review

Uploaded by

Jo Ch
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

22:31 22/10/2023 Stack: Attempt review

Đã bắt đầu vào Thứ hai, 9 Tháng mười 2023, 8:26 AM


lúc
Tình trạng Đã hoàn thành
Hoàn thành vào Chủ nhật, 22 Tháng mười 2023, 10:31 PM
lúc
Thời gian thực 13 ngày 14 giờ
hiện
Điểm 8,00/8,00
Điểm 10,00 của 10,00 (100%)

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 1/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 1
Chính xác

Điểm 1,00 của 1,00

You are keeping score for a basketball game with some new rules. The game consists of several rounds, where the scores of past rounds may affect
future rounds' scores.

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the operation you must apply to the
record, with the following rules:

A non-negative integer x (from 0 to 9) - record a new score of x


'+' - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
'D' - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
'C' - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

Finally, return the sum of all scores in the record.

For example:

ops = "52CD+"

'5' - add to the record. Record now is [5]


'2' - add to the record. Record now is [5,2]
'C' - invalid the previous score (2). Record now is [5]
'D' - Record new score that is double of previous score (5*2). Record now is [5,10]
'+' - Record a new score that is the sum of the previous two scores. Record now is [5,10,15]

Return the sum: 5+10+15 = 30

For example:

Test Result

cout << baseballScore("52CD+"); 30

cout << baseballScore("524CD9++"); 55

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int baseballScore(string ops) {


2 vector<int> record;
3 ▼ for (char op : ops) {
4 ▼ if (op == 'C') {
5 ▼ if (!record.empty()) {
6 record.pop_back();
7 }
8 ▼ } else if (op == 'D') {
9 ▼ if (!record.empty()) {
10 record.push_back(2 * record.back());
11 }
12 ▼ } else if (op == '+') {
13 ▼ if (record.size() >= 2) {
14 int last = record.back();
15 record.pop_back();
16 int secondLast = record.back();
17 record.push_back(last);
18 record.push_back(last + secondLast);
19 }
20 ▼ } else {
21 record.push_back(op - '0');
22 }
23 }
24 int sum = 0;

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 2/22
22:31 22/10/2023 Stack: Attempt review
25 ▼ for (int score : record) {
26 sum += score;
27 }
28 return sum;
29 }

Test Expected Got

 cout << baseballScore("52CD+"); 30 30 

 cout << baseballScore("524CD9++"); 55 55 

 cout << baseballScore("5C4C2C11+D3"); 11 11 

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 3/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 2
Chính xác

Điểm 1,00 của 1,00

Implement all methods in class Stack with template type T. The description of each method is written as comment in frame code.

#ifndef STACK_H
#define STACK_H
#include "DLinkedList.h"
template<class T>
class Stack {
protected:
DLinkedList<T> list;
public:
Stack() {}
void push(T item) ;
T pop() ;
T top() ;
bool empty() ;
int size() ;
void clear() ;
};

#endif

You can use all methods in class DLinkedList without implementing them again. The description of class DLinkedList is written as comment in
frame code.

template <class T>


class DLinkedList
{
public:
class Node; //forward declaration
protected:
Node* head;
Node* tail;
int count;
public:
DLinkedList() ;
~DLinkedList();
void add(const T& e);
void add(int index, const T& e);
T removeAt(int index);
bool removeItem(const T& removeItem);
bool empty();
int size();
void clear();
T get(int index);
void set(int index, const T& e);
int indexOf(const T& item);
bool contains(const T& item);
};

For example:

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 4/22
22:31 22/10/2023 Stack: Attempt review

Test Result

Stack<int> stack; 1 0
cout << stack.empty() << " " << stack.size();

Stack<int> stack; 8

int item[] = { 3, 1, 4, 5, 2, 8, 10, 12 };


for (int idx = 0; idx < 8; idx++) stack.push(item[idx]);

assert(stack.top() == 12);

stack.pop();
stack.pop();

cout << stack.top();

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ void push(T item) {


2 list.add(item);
3 }
4
5 ▼ T pop() {
6 ▼ if (list.empty()) {
7 throw std::out_of_range("Stack is empty");
8 }
9 T item = list.get(list.size() - 1);
10 list.removeAt(list.size() - 1);
11 return item;
12 }
13
14 ▼ T top() {
15 ▼ if (list.empty()) {
16 throw std::out_of_range("Stack is empty");
17 }
18 return list.get(list.size() - 1);
19 }
20
21 ▼ bool empty() {
22 return list.empty();
23 }
24
25 ▼ int size() {
26 return list.size();
27 }
28
29 ▼ void clear() {
30 list.clear();
31 }
32

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 5/22
22:31 22/10/2023 Stack: Attempt review

Test Expected Got

 Stack<int> stack; 1 0 1 0 
cout << stack.empty() << " " << stack.size();

 Stack<int> stack; 8 8 

int item[] = { 3, 1, 4, 5, 2, 8, 10, 12 };


for (int idx = 0; idx < 8; idx++) stack.push(item[idx]);

assert(stack.top() == 12);

stack.pop();
stack.pop();

cout << stack.top();

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 6/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 3
Chính xác

Điểm 1,00 của 1,00

Given an array nums[] of size N having distinct elements, the task is to find the next greater element for each element of the array
Next greater element of an element in the array is the nearest element on the right which is greater than the current element.
If there does not exist a next greater of a element, the next greater element for it is -1

Note: iostream, stack and vector are already included

Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9

Example 1:
Input:
nums = {15, 2, 4, 10}
Output:
{-1, 4, 10, -1}

Example 2:
Input:
nums = {1, 4, 6, 9, 6}
Output:
{4, 6, 9, -1, -1}

For example:

Test Input Result

int N; 4 -1 4 10 -1
cin >> N; 15 2 4 10
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

int N; 5 4 6 9 -1 -1
cin >> N; 1 4 6 9 6
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ vector<int> nextGreater(vector<int>& arr) {


2 vector<int> result(arr.size(), -1);
3 stack<int> s;
4
5▼ for (int i = 0; i < arr.size(); i++) {
6▼ while (!s.empty() && arr[i] > arr[s.top()]) {
7 result[s.top()] = arr[i];
8 s.pop();
9 }
https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 7/22
22:31 22/10/2023 Stack: Attempt review
9 }
10 s.push(i);
11 }
12 return result;
13 }

Test Input Expected Got

 int N; 4 -1 4 10 -1 -1 4 10 -1 
cin >> N; 15 2 4 10
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

 int N; 5 4 6 9 -1 -1 4 6 9 -1 -1 
cin >> N; 1 4 6 9 6
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 8/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 4
Chính xác

Điểm 1,00 của 1,00

Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators will only include the
basic arithmetic operators like *, /, + and -.

Postfix expression: The expression of the form “a b operator” (ab+) i.e., when a pair of operands is followed by an operator.
For example: Given string S is "2 3 1 * + 9 -". If the expression is converted into an infix expression, it will be 2 + (3 * 1) – 9 = 5 – 9 = -4.

Requirement: Write the function to evaluate the value of postfix expression.

For example:

Test Result

cout << evaluatePostfix("2 3 1 * + 9 -"); -4

cout << evaluatePostfix("100 200 + 2 / 5 * 7 +"); 757

Answer: (penalty regime: 0 %)

Reset answer

1 #include <sstream>
2 ▼ int evaluatePostfix(const string& expression) {
3 stack<int> s;
4 stringstream ss(expression);
5 string token;
6 ▼ while (getline(ss, token, ' ')) {
7 ▼ if (token == "+" || token == "-" || token == "*" || token == "/") {
8 int b = s.top();
9 s.pop();
10 int a = s.top();
11 s.pop();
12 ▼ if (token == "+") {
13 s.push(a + b);
14 ▼ } else if (token == "-") {
15 s.push(a - b);
16 ▼ } else if (token == "*") {
17 s.push(a * b);
18 ▼ } else if (token == "/") {
19 s.push(a / b);
20 }
21 ▼ } else {
22 s.push(stoi(token));
23 }
24 }
25 return s.top();
26 }

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 9/22
22:31 22/10/2023 Stack: Attempt review

Test Expected Got

 cout << evaluatePostfix("2 3 1 * + 9 -"); -4 -4 

 cout << evaluatePostfix("100 200 + 2 / 5 * 7 +"); 757 757 

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 10/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 5
Chính xác

Điểm 1,00 của 1,00

A Maze is given as 5*5 binary matrix of blocks and there is a rat initially at the upper left most block i.e., maze[0][0] and the rat wants to eat
food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the
block can be used in the path from source to destination. The rat can move in any direction (not diagonally) to any block provided the block is
not a dead end.

Your task is to implement a function with following prototype to check if there exists any path so that the rat can reach the food or not:
bool canEatFood(int maze[5][5], int fx, int fy);

Template:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
class node {
public:
int x, y;
int dir;
node(int i, int j)
{
x = i;
y = j;

// Initially direction
// set to 0
dir = 0;
}
};
Some suggestions:
- X : x coordinate of the node
- Y : y coordinate of the node
- dir : This variable will be used to tell which all directions we have tried and which to choose next. We will try all the
directions in anti-clockwise manner starting from up.
If dir=0 try up direction.
If dir=1 try left direction.
If dir=2 try down direction.
If dir=3 try right direction.

For example:

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 11/22
22:31 22/10/2023 Stack: Attempt review

Test Result

// Maze matrix 1
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 1 },
{ 0, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 0 },
{ 1, 0, 0, 1, 0 }
};

// Food coordinates
int fx = 1, fy = 4;

cout << canEatFood(maze, fx, fy);

// Maze matrix 1
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 0 }
};

// Food coordinates
int fx = 2, fy = 3;

cout << canEatFood(maze, fx, fy);

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ bool isValid(int maze[5][5], int x, int y, int visited[5][5]) {


2 return (x >= 0 && x < 5 && y >= 0 && y < 5 && maze[x][y] == 1 && !visited[x]
3 }
4
5 ▼ bool canEatFoodUtil(int maze[5][5], int x, int y, int fx, int fy, int visited[5]
6 ▼ if (x == fx && y == fy) {
7 return true;
8 }
9 ▼ if (isValid(maze, x, y, visited)) {
10 visited[x][y] = 1;
11 if (canEatFoodUtil(maze, x + 1, y, fx, fy, visited))
12 return true;
13 if (canEatFoodUtil(maze, x - 1, y, fx, fy, visited))
14 return true;
15 if (canEatFoodUtil(maze, x, y + 1, fx, fy, visited))
16 return true;
17 if (canEatFoodUtil(maze, x, y - 1, fx, fy, visited))
18 return true;
19 visited[x][y] = 0; // Backtrack
20 }
21 return false;
22 }
23
24 ▼ bool canEatFood(int maze[5][5], int fx, int fy) {
25 int visited[5][5] = { {0} };
26 return canEatFoodUtil(maze, 0, 0, fx, fy, visited);
27 }

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 12/22
22:31 22/10/2023 Stack: Attempt review

Test Expected Got

 // Maze matrix 1 1 
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 1 },
{ 0, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 0 },
{ 1, 0, 0, 1, 0 }
};

// Food coordinates
int fx = 1, fy = 4;

cout << canEatFood(maze, fx, fy);

 // Maze matrix 1 1 
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 0 }
};

// Food coordinates
int fx = 2, fy = 3;

cout << canEatFood(maze, fx, fy);

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 13/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 6
Chính xác

Điểm 1,00 của 1,00

Given a string S of characters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made.

Included libraries: vector, list, stack

For example:

Test Result

cout << removeDuplicates("abbaca"); ca

cout << removeDuplicates("aab"); b

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ string removeDuplicates(string S) {
2 stack<char> st;
3 ▼ for (char c : S) {
4 ▼ if (!st.empty() && st.top() == c) {
5 st.pop();
6 ▼ } else {
7 st.push(c);
8 }
9 }
10 string result = "";
11 ▼ while (!st.empty()) {
12 result = st.top() + result;
13 st.pop();
14 }
15 return result;
16 }
17

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 14/22
22:31 22/10/2023 Stack: Attempt review

Test Expected Got

 cout << removeDuplicates("abbaca"); ca ca 

 cout << removeDuplicates("aab"); b b 

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 15/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 7
Chính xác

Điểm 1,00 của 1,00

Vietnamese version:

Bài toán stock span là một bài toán về chủ đề kinh tế tài chính, trong đó ta có thông tin về giá của một cổ phiếu qua từng ngày. Mục tiêu của
bài toán là tính span của giá cổ phiếu ở từng ngày.
Span của giá cổ phiếu tại ngày thứ i (ký hiệu là Si) được định nghĩa là số ngày liên tục nhiều nhất liền trước ngày thứ i có giá cổ phiếu thấp hơn,
cộng cho 1 (cho chính nó).

Ví dụ, với chuỗi giá cổ phiếu là [100, 80, 60, 70, 60, 75, 85].

1. Ngày thứ 0 không có ngày liền trước nên S0 bằng 1.


2. Ngày thứ 1 có giá nhỏ hơn giá ngày thứ 0 nên S1 bằng 1.
3. Ngày thứ 2 có giá nhỏ hơn giá ngày thứ 1 nên S2 bằng 1.
4. Ngày thứ 3 có giá lớn hơn giá ngày thứ 2 nên S3 bằng 2.
5. Ngày thứ 4 có giá nhỏ hơn giá ngày thứ 3 nên S4 bằng 1.
6. Ngày thứ 5 có giá lớn hơn giá ngày thứ 4, 3, 2 nên S5 bằng 4.
7. Ngày thứ 6 có giá lớn hơn giá ngày thứ 5, 4, 3, 2, 1 nên S6 bằng 6.

Kết quả sẽ là [1, 1, 1, 2, 1, 4, 6].

Yêu cầu. Viết chương trình tính toán chuỗi span từ chuỗi giá cổ phiếu từ đầu vào.

Input. Các giá trị giá cổ phiếu, cách nhau bởi các ký tự khoảng trắng, được đưa vào standard input.

Output. Các giá trị span, cách nhau bởi một khoảng cách, được xuất ra standard ouput.

(Nguồn: Geeks For Geeks)

=================================

Phiên bản tiếng Anh:


The stock span problem is a financial problem where we have a series of daily price quotes for a stock and we need to calculate the span of
the stock’s price for each day.
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which
the price of the stock on the current day is less than its price on the given day, plus 1 (for itself).
For example: take the stock's price sequence [100, 80, 60, 70, 60, 75, 85]. (See image above)
The given input span for 100 will be 1, 80 is smaller than 100 so the span is 1, 60 is smaller than 80 so the span is 1, 70 is greater than 60 so
the span is 2 and so on.
Hence the output will be [1, 1, 1, 2, 1, 4, 6].

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 16/22
22:31 22/10/2023 Stack: Attempt review
Requirement. Write a program to calculate the spans from the stock's prices.

Input. A list of whitespace-delimited stock's prices read from standard input.

Output. A list of space-delimited span values printed to standard output.

(Source: Geeks For Geeks)


For example:

Input Result

100 80 60 70 60 75 85 1 1 1 2 1 4 6

10 4 5 90 120 80 1 1 2 4 5 1

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ vector<int> stock_span(const vector<int>& ns) {


2 int n = ns.size();
3 vector<int> spans(n, 1);
4
5 ▼ for (int i = 0; i < n; i++) {
6 int counter = 1;
7 int j = i - 1;
8 ▼ while (j >= 0 && ns[i] > ns[j]) {
9 counter += spans[j];
10 j -= spans[j];
11 }
12 spans[i] = counter;
13 }
14
15 return spans;
16 }

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 17/22
22:31 22/10/2023 Stack: Attempt review

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 18/22
22:31 22/10/2023 Stack: Attempt review

Input Expected Got

 100 80 60 70 60 75 85 1 1 1 2 1 4 6 1 1 1 2 1 4 6 

 10 4 5 90 120 80 1 1 2 4 5 1 1 1 2 4 5 1 

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 19/22
22:31 22/10/2023 Stack: Attempt review

Câu hỏi 8
Chính xác

Điểm 1,00 của 1,00

Given a string s containing just the characters '(', ')', '[', ']', '{', and '}'. Check if the input string is valid based on following rules:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

For example:

String "[]()" is a valid string, also "[()]".


String "[])" is not a valid string.

Your task is to implement the function


bool isValidParentheses (string s){
/*TODO*/
}

Note: The library stack of C++ is included.

For example:

Test Result

cout << isValidParentheses("[]"); 1

cout << isValidParentheses("[]()"); 1

cout << isValidParentheses("[)"); 0

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ bool isValidParentheses(string s) {
2 stack<char> stack;
3 ▼ for (char c : s) {
4 ▼ if (c == '(' || c == '[' || c == '{') {
5 stack.push(c);
6 ▼ } else {
7 ▼ if (stack.empty()) {
8 return false;
9 }
10 ▼ if ((c == ')' && stack.top() != '(') || (c == ']' && stack.top() !=
11 return false;
12 }
13 stack.pop();
14 }
15 }
16 return stack.empty();
17 }

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 20/22
22:31 22/10/2023 Stack: Attempt review

Test Expected Got

 cout << isValidParentheses("[]()"); 1 1 

 cout << isValidParentheses("[)"); 0 0 

Passed all tests! 

Chính xác
Điểm cho bài nộp này: 1,00/1,00.

BÁCH KHOA E-LEARNING

WEBSITE

HCMUT
MyBK
BKSI

LIÊN HỆ

 268 Lý Thường Kiệt, P.14, Q.10, TP.HCM

 (028) 38 651 670 - (028) 38 647 256 (Ext: 5258, 5234)

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 21/22
22:31 22/10/2023 Stack: Attempt review
[email protected]

Copyright 2007-2022 BKEL - Phát triển dựa trên Moodle

https://e-learning.hcmut.edu.vn/mod/quiz/review.php?attempt=1436093&cmid=188424 22/22

You might also like