jemin0619 2024. 1. 25. 12:05

https://www.youtube.com/watch?v=0DsyCXIN7Wg

스택 강의

 

https://www.acmicpc.net/problem/10828

 

10828번: 스택

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

www.acmicpc.net

#include <bits/stdc++.h>
using namespace std;

int main(){
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n;
  stack<int> st;
  cin>>n;
  while(n--){
  	string str;
  	cin>>str;
  	if(str=="push"){
  		int a;
		cin>>a;
		st.push(a);
	}
  	if(str=="pop"){
  		if(st.empty()) cout<<-1<<"\n";
  		else{
		  cout<<st.top()<<"\n";
  		  st.pop();
  		}
	}
  	if(str=="size") cout<<st.size()<<"\n";
  	if(str=="empty") cout<<st.empty()<<"\n"; 
  	if(str=="top"){
  		if(st.empty()) cout<<-1<<"\n";
  		else cout<<st.top()<<"\n";
	  }
  }
  return 0;
}

https://www.acmicpc.net/problem/10773

 

10773번: 제로

첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000) 이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경

www.acmicpc.net

#include <bits/stdc++.h>
using namespace std;

int main(){
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n,input,sum=0;
  stack<int> ST;
  cin>>n;
  for(int i=0;i<n;i++){
  	cin>>input;
  	if(input==0) ST.pop();
  	else ST.push(input);
  }
  while(!ST.empty()){
  	sum+=ST.top();
  	ST.pop();
  }
  cout<<sum;
  return 0;
}

 

처음에 문제를 보고 굳이 스택이 필요한가? 란 생각이 들어서 입력과 동시에 sum을 계산했는데 0이 연속으로 나올 경우 문제가 생겨서 스택을 써야 함을 알 수 있었다.