Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### стек с максимумом
- #include <iostream>
- #include <sstream>
- #include <string>
- class Stack
- {
- private:
- struct X {
- int value;
- int localMax;
- };
- X *data_;
- int size;
- int top = -1;
- public:
- Stack(int n): data_(new X[n]), size(n), top(-1) { }
- void push(int value)
- {
- ++top;
- if (top == -1)
- {
- data_[top].value = value;
- data_[top].localMax = value;
- }
- else
- {
- data_[top].value = value;
- data_[top].localMax = data_[top-1].localMax < value ? value : data_[top-1].localMax;
- }
- }
- void pop() { --top; }
- int max() const {return data_[top].localMax; }
- };
- void test1(std::istream &cin, std::ostream & cout)
- {
- int n;
- cin >> n;
- Stack stack(n);
- std::string command;
- int value;
- while (n--) {
- cin>> command;
- if (command == "push")
- {
- cin >> value;
- stack.push(value);
- }
- else if (command == "pop") { stack.pop();}
- else if (command == "max") { cout << stack.max() << "\n"; }
- }
- }
- int main(int argc, char *argv[])
- {
- {
- std::istringstream istr(std::string("5 push 1 push 2 max pop max"));
- std::string answer;
- std::ostringstream ostr(answer);
- test1(istr, ostr);
- std::cout << "ответ:\n" << ostr.str() << "\n";
- std::cout << "верный ответ 2 1 \n";
- }
- {
- std::istringstream istr("10 push 2 push 3 push 9 push 7 push 2 max max max pop max");
- test1(istr, std::cout);
- std::cout << "верный ответ 9 9 9 9 \n";
- }
- {
- std::istringstream istr("5 push 2 push 1 max pop max");
- test1(istr, std::cout);
- std::cout << "верный ответ 2 2 \n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment