알고리즘 분류
구현
자료 구조
스택
문제 해결 아이디어
Stack을 이용하여 입력받은 숫자를 넣고 0이 입력되면 pop()하여 가장 최근에 들어온 숫자를 지운다.
이 과정을 다 하면 stack에 남아있는 숫자를 더하면 된다.
코드
#include <iostream>
#include <stack>
using namespace std;
int main()
{
int k;
stack<int> s;
cin >> k;
int input;
for (int i = 0; i < k; i++)
{
cin >> input;
if (input != 0) s.push(input);
else
{
if (!s.empty())
s.pop();
}
}
int cnt = 0;
while (!s.empty())
{
cnt += s.top();
s.pop();
}
cout << cnt;
}
'Algorithm > 스택과 큐' 카테고리의 다른 글
백준 오큰수(17298) C++ 풀이 (0) | 2023.01.28 |
---|---|
백준 옥상 정원 꾸미기(6198) C++ 풀이 (0) | 2023.01.28 |
백준 탑(2493) C++ 풀이 (0) | 2023.01.28 |
백준 스택 수열(1874) C++ 풀이 (0) | 2023.01.28 |
백준 스택(10828) C++ 풀이 (0) | 2023.01.28 |