λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Algorithm

[SW Expert Academy] - (D3)8931. 제둜(Stack)

by 주발2 2020. 7. 12.
λ°˜μ‘ν˜•

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AW5jBWLq7jwDFATQ&categoryId=AW5jBWLq7jwDFATQ&categoryType=CODE

 

SW Expert Academy

SW ν”„λ‘œκ·Έλž˜λ° μ—­λŸ‰ 강화에 도움이 λ˜λŠ” λ‹€μ–‘ν•œ ν•™μŠ΅ 컨텐츠λ₯Ό ν™•μΈν•˜μ„Έμš”!

swexpertacademy.com

μ½”λ“œ

import java.util.Scanner;
import java.util.Stack;

public class Solution {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int t = scan.nextInt();
		for(int tc=1; tc<=t; tc++) {
			int K = scan.nextInt();
			Stack<Integer> stack = new Stack<>();
			int sum = 0;
			
			for(int i=0; i<K; i++) {
				int num = scan.nextInt();
				
				// 0일경우 κ°€μž₯ λ§ˆμ§€λ§‰ 수λ₯Ό λΉΌκ³ , 0이 μ•„λ‹κ²½μš° μŠ€νƒμ— λ„£κΈ°
				if(num == 0) {
					stack.pop();
				} else {
					stack.push(num);
				}
			}
			
			// μŠ€νƒμ˜ λͺ¨λ“  μš”μ†Œλ“€ λ”ν•˜κΈ°.
			while(!stack.isEmpty()) {
				sum += stack.pop();
			}
			System.out.println("#" + tc + " " + sum);
		}
		
		scan.close();
	}

}

풀이

λ¬Έμ œμ—μ„œ 핡심뢀뢄은 λ‹€μŒμ΄λ‹€.

 

0을 μ™Έμ³μ„œ κ°€μž₯ μ΅œκ·Όμ— 썼던 수λ₯Ό μ§€μš΄λ‹€.

 

μœ„ λ¬Έμž₯으둜 μŠ€νƒμ„ μœ μΆ”ν•  수 μžˆλ‹€.

λ¬Έμ œμ—μ„œ μŠ€νƒμ— λΉ„μ–΄μžˆλŠ” μƒνƒœμ—μ„œ 0μ΄μ˜€λŠ” 상황은 μ•ˆμ˜€λŠ” 것 κ°™λ‹€.

λ”°λΌμ„œ 0μΌλ•ŒλŠ” μ΅œκ·Όκ°’μ„ μ§€μš°κ³ (pop), 0이 μ•„λ‹λ•ŒλŠ” μŠ€νƒμ— λ„£λŠ”λ‹€(push)

κ·Έ ν›„ μŠ€νƒμ˜ λͺ¨λ“  μš”μ†Œλ“€μ„ λ”ν•˜λ©΄ λœλ‹€.

 

μ €λ²ˆμ—λŠ” μ‹œκ°„μ΄ˆκ³Όκ°€ λ°œμƒν–ˆμ—ˆλŠ”λ°, ArrayList둜 ν’€κ³  μš”μƒν•˜κ²Œ ν’€μ–΄μ„œ μ‹œκ°„μ΄ˆκ³Όκ°€ λ°œμƒν–ˆμ—ˆλ‹€.

 

λ°˜μ‘ν˜•

λŒ“κΈ€