[SWEA] 제로

문제 보러가기

제한사항

만약 정수가 0일 경우에는 최근에 쓰고 지우지 않았던 수를 지워야 하며, 그렇지 않을 경우 해당 수를 써야 한다.

정수가 0일 경우에 지울 수 있는 수가 있음을 보장할 수 있다.

첫번째 생각

문제를 읽자마자 Stack이 생각났다.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;
import java.util.Stack;

public class Solution {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for(int tc=1;tc<=T;tc++) {
			int K = sc.nextInt();
			Stack<Integer> stack = new Stack<Integer>();
			for(int i=0; i<K; i++) {
				int n = sc.nextInt();
				if ( n != 0 ) stack.add(n);
				else stack.pop();
			}
			int ans = 0;
			while(!stack.isEmpty()) {
				ans += stack.pop();
			}
			System.out.println("#"+tc+" "+ans);
		}
	}
}