#include <iostream>
using namespace std;
class Stack
{
public:
Stack(int k)
{
this->length = k;
this->top = -1;
this->arr = new int[length];
}
~Stack()
{
delete[] arr;
}
void insert(int n)
{
top++;
arr[top] = n;
}
bool isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
int size()
{
return top + 1;
}
int pop()
{
if (top == -1)
return -1;
else
{
top--;
return arr[top + 1];
}
}
int getTop()
{
if (top == -1)
return -1;
else
{
return arr[top];
}
}
private:
int length;
int top;
int* arr;
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, command, num;
cin >> n;
Stack Mystack = Stack(n - 1);
for (int i = 0; i < n; i++)
{
cin >> command;
switch (command)
{
case 1:
cin >> num;
Mystack.insert(num);
break;
case 2:
cout << Mystack.pop() << '\n';
break;
case 3:
cout << Mystack.size() << '\n';
break;
case 4:
cout << Mystack.isEmpty() << '\n';
break;
case 5:
if (Mystack.isEmpty())
cout << -1 << '\n';
else
{
cout << Mystack.getTop() << '\n';
}
break;
}
}
}
첫 시도 때 시간초과가 떠서 아래의 코드를 메인 함수에 넣어줬다. 두 줄로 바로 해결되었다.
ios_base::sync_with_stdio(false);
cin.tie(NULL);
문제에서의 입력의 양이 많기 때문에 빠른 입출력 방식을 사용해야 했다.
문제: https://www.acmicpc.net/problem/28278
28278번: 스택 2
첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000) 둘째 줄부터 N개 줄에 명령이 하나씩 주어진다. 출력을 요구하는 명령은 하나 이상 주어진다.
www.acmicpc.net
'Baekjoon > C++' 카테고리의 다른 글
[백준 1181번] 단어 정렬 (0) | 2024.01.08 |
---|---|
[백준 1094번] 막대기 (0) | 2023.10.08 |
[백준 1018번] 체스판 다시 칠하기 (0) | 2023.09.24 |
[백준 1009번] 분산처리 (0) | 2023.07.25 |
[백준 1012번] 유기농 배추 (0) | 2023.07.25 |