Post

[BaekJoon] 10773번 - 제로 [Java][C++]

[BaekJoon] 10773번 - 제로 [Java][C++]

문제 링크


1. 문제 풀이


$K$ 개의 수에 대해 $0$ 이면 최근에 쓴 수를 지우고 아니면 쓴다는 점에서 스택 자료구조를 활용하면 간단하게 해결할 수 있다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        Deque<Integer> stack = new ArrayDeque<>();

        int K = Integer.parseInt(br.readLine());
        for (int i = 0; i < K; i++) {
            int n = Integer.parseInt(br.readLine());

            if (n == 0) {
                stack.pop();
            } else {
                stack.push(n);
            }
        }

        int sum = 0;
        while (!stack.isEmpty()) {
            sum += stack.pop();
        }

        System.out.println(sum);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    stack<int> st;

    int k;
    cin >> k;

    for (int i = 0; i < k; i++) {
        int n;
        cin >> n;

        if (n == 0) {
            st.pop();
        } else {
            st.push(n);
        }
    }

    int sum = 0;
    while (!st.empty()) {
        sum += st.top();
        st.pop();
    }

    cout << sum;
}

This post is licensed under CC BY 4.0 by the author.