제로 (10773번)
https://www.acmicpc.net/problem/10773
풀이방법
- 스택을 이용해 입력값이
0
인 경우pop
을 하고0
이 아니라면 해당 값을push
한다.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static class Stack {
int pos = 0;
int countOfData = 0;
int[] array = null;
public Stack(int size) {
array = new int[size];
}
public int pop() {
countOfData--;
int rData = array[--pos];
array[pos] = 0;
return rData;
}
public void push(int c) {
array[pos++] = c;
countOfData++;
}
public boolean isEmpty() {
return (countOfData == 0);
}
public int size() {
return countOfData;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int K = Integer.parseInt(br.readLine());
Stack stack = new Stack(K);
int value = 0;
int sum = 0;
while (K-- > 0) {
value = Integer.parseInt(br.readLine());
if (value == 0 && !stack.isEmpty()) sum -= stack.pop();
else {
sum += value;
stack.push(value);
}
}
System.out.println(sum);
}
}
Comments powered by Disqus.