on my way
[GDSC Week2-1] 백준 10828번:: 스택 (C++) 본문
반응형
* 생각한 아이디어 및 문제 풀이
0. 처음에 명령의 수는 int로 입력받는다.
1. 각 명령은 STRING으로 받아서 앞에 해당하는 명령이 있으면 그 부분을 각 명령에 맞게 실행한다.2. 명령을 받는 것은 각각의 문자수 다음만큼의 수부터 끝까지 받고, substr로 처리한다.
3. 처음에는 문장 전체를 받는다고 생각했으나, 어차피 띄어쓰기가 있으니 그냥 해당하는 문자를 받으면 다음 숫자를 입력받아 명령을 시행해야겠다고 생각했다.
* 코드
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N, num;
cin >> N;
string input;
stack<int> s;
for(int i=0; i<N; i++){
cin >> input;
if(input=="push"){
cin >> num;
s.push(num);
} else if (input == "pop"){
if(s.empty()==true){
cout << "-1" << '\n';
} else {
cout << s.top() << '\n';
s.pop();
}
} else if (input == "size"){
cout << s.size() <<'\n';
} else if (input == "empty"){
cout << s.empty() << '\n';
} else if (input=="top"){
if(s.empty() == true){
cout << "-1" << '\n';
} else{
cout << s.top() << '\n';
}
}
}
}
* 회고
stack을 푸는 문제라 스택을 그냥 구현하는 방식으로 다시 풀이해보았다.
그러나 오히려 메모리가 조금 더 소요되었다.
#include <iostream>
using namespace std;
int pos;
int dat[10001];
void push(int x) {
dat[pos] = x;
pos++;
}
int pop() {
if (pos == 0) return -1;
int top = dat[pos - 1];
pos--;
return top;
}
int size() {
return pos;
}
int top() {
if (pos == 0) return -1;
return dat[pos - 1];
}
int empty() {
if (pos == 0) return 1;
else return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N;
cin >> N;
while (N--) {
string str;
cin >> str;
if (str == "push") {
int n;
cin >> n;
push(n);
}
else if (str == "pop") {
cout << pop() << '\n';
}
else if (str == "top") {
cout << top() << '\n';
}
else if (str == "size") {
cout << size() << '\n';
}
else if (str == "empty") {
cout << empty() << '\n';
}
}
}
매우 간단한 문제들을 내가 생각보다 꼬아 생각하는 경우가 있어서 앞으로 조심해야겠다.
* 문제 링크 : https://www.acmicpc.net/problem/10828
반응형
'algorithm > C++' 카테고리의 다른 글
[GDSC Week2-3] 백준 2346번:: 풍선 터뜨리기 (C++) (0) | 2021.10.11 |
---|---|
[GDSC Week2-2] 백준 10828번:: 스택 (C++) (0) | 2021.10.11 |
카카오 공채 코딩테스트:: 압축 (C++) (0) | 2021.10.09 |
[GDSC Week1-4] 백준 1448번:: 삼각형만들기 (C++) (0) | 2021.10.03 |
[GDSC Week1-3] 백준 11582번:: 치킨 TOP N (C++) (0) | 2021.10.03 |