[algorithm] 백준 10773번 제로

2026. 1. 12. 20:09·algorithm/스택
반응형

 

#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
'algorithm/스택' 카테고리의 다른 글
  • [algorithm] 백준 3986번 좋은 단어
  • [algorithm] 백준 9012번 괄호
  • [algorithm] 백준 4949번 균형잡힌 세상
  • [algorithm] 백준 10828번 스택
20puddle
20puddle
20puddle 님의 블로그 입니다.
  • 20puddle
    20puddle 님의 블로그
    20puddle
  • 전체
    오늘
    어제
    • 분류 전체보기 (100)
      • Spring boot (5)
      • git & github (5)
      • algorithm (47)
        • theory (3)
        • 배열 (7)
        • 연결 리스트 (3)
        • 스택 (5)
        • 큐 (3)
        • 덱 (2)
        • 기초 코드 (19)
        • BFS (5)
      • AI (43)
        • Machine Learning (35)
        • Deep Learning (8)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    인공지능
    알고리즘
    딥러닝
    Spring Boot
    Java
    오프라인 학습
    ML
    Aimers
    게시판
    머신러닝
    주성분변환
    백준
    git
    AI
    그레디언트 클리핑
    홀드아웃 검증
    list
    연결리스트
    DL
    github
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.3
20puddle
[algorithm] 백준 10773번 제로
상단으로

티스토리툴바