반응형

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
int x;
int s;
int res=0;
cin >> n;
stack<int> st;
for(int tmp=0; tmp<n; tmp++)
{
cin >> x;
if(x == 0)
{
st.pop();
}
else
{
st.push(x);
}
}
while(st.size() != 0)
{
s = st.top();
res += s;
st.pop();
}
cout << res;
return 0;
}
입력값이 0이면 pop하고
0이 아니면 push하면 되는 아주아주 간단한 문제다
n번 입력과정이 끝나면
스택 크기가 0이될때까지
top의 값을 더해주고 pop() 하는걸 반복한다
지금와서 보이는건데
굳이 변수 s를 선언하지 않고
while(st.size() != 0)
{
res += st.top();
st.pop();
}
이런식으로 처리하는게 더 깔끔한거 같다
반응형
'algorithm > 스택' 카테고리의 다른 글
| [algorithm] 백준 3986번 좋은 단어 (0) | 2026.01.25 |
|---|---|
| [algorithm] 백준 9012번 괄호 (0) | 2026.01.25 |
| [algorithm] 백준 4949번 균형잡힌 세상 (0) | 2026.01.25 |
| [algorithm] 백준 10828번 스택 (0) | 2026.01.12 |
