on my way

[GDSC Week2-1] 백준 10828번:: 스택 (C++) 본문

algorithm/C++

[GDSC Week2-1] 백준 10828번:: 스택 (C++)

wingbeat 2021. 10. 11. 20:14
반응형

 

 

* 생각한 아이디어 및 문제 풀이

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

반응형